The user wants a Python Command Line Interface (CLI) tool that converts text files from one encoding to another.
Key requirements:
- Input: A source file path.
- Output: A destination file path (optional, maybe overwrite or create a new one).
- Parameters:
- Source encoding (optional, try to detect if not provided).
- Target encoding (required).
- Functionality: Read the file, decode it, encode it, write it back.
- Interface: CLI using
argparse or a third-party library like click or typer. argparse is standard library and sufficient for a basic tool, but typer is more modern. Let's stick to argparse to keep it dependency-free (except for optional charset detection) or provide a version using standard libraries only for maximum portability.
Let's refine the logic:
- Encoding Detection: Python's standard library doesn't have robust charset detection.
cchardet or chardet are popular 3rd party libs. For a "pure" python script, I should probably ask the user for the source encoding or assume UTF-8/system default. However, adding an optional dependency for detection makes the tool much better. I will write the code to use chardet if available, otherwise default to utf-8 or ask the user.
Let's draft the structure using argparse.
Arguments:
input_file: positional.
-o, --output: optional output file. If missing, maybe print to stdout or modify in place? Modifying in place is risky. Let's make output required or default to stdout to be unix-philosophy compliant, or just require a distinct output file for safety. Let's require an output file for a "conversion" tool.
-f, --from-encoding: Source encoding. Optional (try to detect/assume utf-8).
-t, --to-encoding: Target encoding. Required.
Error Handling:
- File not found.
- Decoding errors (UnicodeDecodeError).
- Encoding errors (UnicodeEncodeError).
Code Structure:
- Imports (
argparse, os, sys).
- Main function setup.
- Argument parsing.
- The conversion logic:
- Open input in binary mode (
rb).
- Read bytes.
- Detect encoding if not set.
- Decode to string.
- Encode to target.
- Write to output file.
Refinement on Encoding Detection:
I will implement a fallback mechanism.
- If user provides
-f, use that.
- If not, try
chardet (if installed).
- If not installed, default to
utf-8 (safest bet for modern text) but warn the user.
Refinement on Output:
If output file is the same as input file, we need to write to a temp file first, then replace, to avoid data loss on failure.
Let's write the solution using the standard library argparse to make it run everywhere without pip install (except for optional detection).
Plan:
- Shebang & Imports: Standard stuff.
- Function
convert_file:
- Logic to handle reading/writing.
- Handling
errors argument (ignore, replace, strict).
- Function
detect_encoding: Helper to use chardet if available.
- Main execution block:
argparse setup.
Let's add some "bells and whistles" like progress output (printing what is happening).
Self-Correction/Alternative:
Using click makes the code cleaner but adds a dependency. The prompt asks for a "Python CLI tool". Usually, standard library is preferred for simple scripts unless advanced features are needed. I will stick to argparse but mention chardet for auto-detection.
Detailed Logic for convert_file:
def convert_file(input_path, output_path, from_enc=None, to_enc='utf-8', errors='strict'):
# Read binary
with open(input_path, 'rb') as f:
content_bytes = f.read()
# Determine source encoding
if not from_enc:
# Try detection logic
from_enc = 'utf-8' # Fallback
# Decode
text_content = content_bytes.decode(from_enc, errors=errors)
# Write (text mode handles encoding)
with open(output_path, 'w', encoding=to_enc, errors=errors) as f:
f.write(text_content)
Wait, if input and output are the same, standard text write w truncates immediately. If decoding fails later, data is lost.
Safe approach: Read all content into memory (if file is small/medium) or write to a temporary file and os.replace it.
For a generic tool, assuming files fit in memory is usually okay for text, but streaming is better. However, encoding conversion often requires knowing the whole context or is stateless. For simple text encodings, streaming is fine.
Let's stick to read-all-then-write for simplicity in this example, but handle the "overwrite" case by writing to a buffer/string first.
Features to include:
- Input file argument.
- Output file argument.
- Source encoding (optional, default utf-8).
- Target encoding (required).
- Error handling strategy (strict, ignore, replace).
- List encodings option (helpful).
Drafting the code:
I will provide a complete script.
Step 1: Imports
argparse, sys, os.
Step 2: Encoding Detection
I will check if chardet is available. If so, use it. If not, warn and default.
Step 3: The Parser
Setup argparse.ArgumentParser.
Step 4: The Logic
Read -> Decode -> Encode -> Write.
Step 5: Execution
if __name__ == "__main__":
Bonus:
Add a --list flag to show available python encodings using encodings.aliases.aliases.
Let's put it together.
Constraints check:
- Input text file.
- Convert encodings.
- CLI.
Edge cases:
- File doesn't exist.
- Permission denied.
- Invalid encoding name provided by user.
- Corrupt text (mismatch between actual encoding and specified source encoding).
I will write the code now. I'll make it robust.
import argparse
import sys
import os
# ... logic ...
I will also provide instructions on how to run it and how to install chardet if they want auto-detection.
Let's refine the errors parameter. Python's open() supports 'strict', 'ignore', 'replace', 'surrogateescape', 'xmlcharrefreplace', 'backslashreplace'. 'strict' is default. Passing this through is good practice.
Final check on the "overwrite" scenario.
If input_file == output_file:
- Read content.
- Decode.
- Write to temporary file (or keep in memory).
- Move/Overwrite original.
If I just do:
text = open(in, 'r', encoding=src).read()
open(out, 'w', encoding=dst).write(text)
If in == out, the open(out, 'w') truncates in before in is read (depending on OS/Buffering, but generally risky). Actually, open(..., 'w') truncates immediately. So if I open the output file for writing first, I lose the input.
The sequence must be: Open Input -> Read -> Close Input -> Open Output -> Write -> Close Output.
If the file is the same, this is safe if the OS allows reading a deleted/open file (Unix does) but open(out, 'w') clears the file content.
So:
with open(input, 'rb') as f: data = f.read()
text = data.decode(...)
with open(output, 'w', ...) as f: f.write(...)
If input == output:
Step 1 reads the file.
Step 3 opens the same file in w mode, which truncates it to 0 bytes. Then writes text.
This works fine provided step 1 successfully read the data into memory.
I will structure the answer with:
- The complete Python code.
- Instructions on how to use it.
- Optional dependency note (
chardet).
One specific feature: listing common encodings. python -c "import encodings; print(...)". I can bake this into the CLI as --list-encodings.
Let's finalize the script.
#!/usr/bin/env python3
import argparse
import sys
import os
import codecs
def main():
parser = argparse.ArgumentParser(description="Convert text file encodings.")
parser.add_argument("input_file", help="Path to the source file.")
parser.add_argument("-o", "--output", help="Path to the destination file. If omitted, output is printed to stdout.")
parser.add_argument("-f", "--from-enc", help="Source encoding. If omitted, attempts auto-detection (requires 'chardet') or falls back to 'utf-8'.")
parser.add_argument("-t", "--to-enc", default="utf-8", help="Target encoding (default: utf-8).")
parser.add_argument("--errors", default="strict", choices=['strict', 'ignore', 'replace', 'surrogateescape', 'xmlcharrefreplace', 'backslashreplace'], help="Error handling scheme.")
parser.add_argument("--list", action="store_true", help="List common available encodings.")
args = parser.parse_args()
# ... implementation ...
Wait, codecs.lookup can validate if an encoding exists. I should use that to fail fast if user provides a bad encoding name.
Implementation details:
If output is stdout, I should write to sys.stdout.
If output is file, write to file.
Handling the chardet dependency:
I'll wrap the import in a try...except block.
Okay, ready to generate the response. I will produce a clean, well-commented script.
Here is a complete, robust Python CLI tool to convert text file encodings. It uses the standard argparse library so it works out-of-the-box with any Python installation.
The Python Script (convert_encoding.py)
Save the following code into a file named convert_encoding.py.
import argparse
import os
import sys
import codecs
# Optional: Attempt to import chardet for automatic encoding detection
try:
import chardet
HAS_CHARDET = True
except ImportError:
HAS_CHARDET = False
def detect_encoding(file_path):
"""Detects file encoding using the chardet library."""
if not HAS_CHARDET:
print("Error: 'chardet' library is required for auto-detection.", file=sys.stderr)
print("Please install it using: pip install chardet", file=sys.stderr)
sys.exit(1)
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
return result['encoding']
def list_encodings():
"""Lists common Python encodings."""
common_encodings = [
'utf-8', 'ascii', 'latin-1', 'cp1252', 'iso-8859-1',
'utf-16', 'utf-32', 'gbk', 'big5', 'shift_jis'
]
print("Common available encodings:")
for enc in common_encodings:
print(f" - {enc}")
print("\nNote: Python supports many other encodings. See Python docs for full list.")
def convert_file(input_path, output_path, from_enc, to_enc, errors):
"""
Reads a file with source encoding and writes to a new file with target encoding.
"""
# Resolve absolute paths
input_path = os.path.abspath(input_path)
# If output is not specified, overwrite the input file
if output_path is None:
output_path = input_path
else:
output_path = os.path.abspath(output_path)
# 1. Determine Source Encoding
source_encoding = from_enc
if from_enc.lower() == 'auto':
print(f"Detecting encoding for {input_path}...")
source_encoding = detect_encoding(input_path)
print(f"Detected: {source_encoding}")
# 2. Validate Encodings
try:
codecs.lookup(source_encoding)
except LookupError:
print(f"Error: Source encoding '{source_encoding}' is not supported.", file=sys.stderr)
sys.exit(1)
try:
codecs.lookup(to_enc)
except LookupError:
print(f"Error: Target encoding '{to_enc}' is not supported.", file=sys.stderr)
sys.exit(1)
# 3. Perform Conversion
try:
# Read content using a binary read to avoid system default encoding issues,
# then decode manually.
with open(input_path, 'rb') as f_in:
content_bytes = f_in.read()
# Decode string from bytes
text_content = content_bytes.decode(source_encoding, errors=errors)
# Encode string back to bytes using target encoding
output_bytes = text_content.encode(to_enc, errors=errors)
# Write bytes to output file
with open(output_path, 'wb') as f_out:
f_out.write(output_bytes)
print(f"Success: Converted '{input_path}' ({source_encoding}) -> '{output_path}' ({to_enc})")
except FileNotFoundError:
print(f"Error: Input file '{input_path}' not found.", file=sys.stderr)
except Exception as e:
print(f"Error during conversion: {e}", file=sys.stderr)
def main():
parser = argparse.ArgumentParser(
description="A CLI tool to convert text files between encodings.",
epilog="Example: python convert_encoding.py data.txt -f utf-8 -t ascii -o data_ascii.txt"
)
parser.add_argument("input_file", help="Path to the source file")
parser.add_argument("-o", "--output", help="Path to the output file (overwrites source if omitted)")
parser.add_argument(
"-f", "--from",
dest="from_enc",
default="auto",
help="Source encoding (default: auto-detect). Use 'auto' requires 'chardet' installed."
)
parser.add_argument(
"-t", "--to",
dest="to_enc",
default="utf-8",
help="Target encoding (default: utf-8)"
)
parser.add_argument(
"--errors",
default="strict",
choices=['strict', 'ignore', 'replace'],
help="How to handle encoding errors (default: strict)"
)
parser.add_argument(
"--list",
action="store_true",
help="List common encodings and exit"
)
args = parser.parse_args()
if args.list:
list_encodings()
sys.exit(0)
convert_file(args.input_file, args.output, args.from_enc, args.to_enc, args.errors)
if __name__ == "__main__":
main()
How to use it
You can run this tool from your terminal (Command Prompt, PowerShell, or Bash).
1. Basic Conversion
Convert a file named input.txt (detected automatically) to UTF-8 and save it as output.txt:
python convert_encoding.py input.txt -o output.txt
2. Specify Encodings Explicitly
Convert a file from Windows-1252 to UTF-8:
python convert_encoding.py legacy_file.txt -f cp1252 -t utf-8
3. Overwrite the Original File
If you omit the -o flag, the script will convert the file and save it back to the original path:
python convert_encoding.py data.txt -f latin-1 -t utf-8
4. Handle Unconvertible Characters
If your text contains characters that cannot be represented in the target encoding (e.g., emojis in ASCII), the script will crash by default (strict). You can use --errors replace to put a placeholder (like ?) instead:
python convert_encoding.py readme.txt -t ascii --errors replace
Optional: Auto-Detection
The script supports --from auto. To use this feature, you need the chardet library:
pip install chardet
Once installed, you can run:
python convert_encoding.py mystery_file.txt -t utf-8