python
#!/usr/bin/env python3
"""
Text file encoding converter CLI tool.
Usage:
python encodeconv.py input.txt --target utf-8
python encodeconv.py *.txt --source cp1252 --target utf-8 --output-dir ./converted/
python encodeconv.py file.txt --detect-source --target utf-8 -v
Requires: Python 3.6+
Optional: pip install chardet # for --detect-source
"""
import argparse
import os
import sys
from pathlib import Path
try:
import chardet
HAS_CHARDET = True
except ImportError:
HAS_CHARDET = False
def detect_encoding(file_path: Path) -> str:
"""Detect encoding using chardet."""
if not HAS_CHARDET:
raise ImportError("chardet is required for --detect-source. Install with: pip install chardet")
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
encoding = result['encoding']
confidence = result['confidence']
if confidence < 0.7:
print(f"Warning: Low confidence ({confidence:.2f}) for detected encoding '{encoding}'", file=sys.stderr)
return encoding
def convert_file(input_path: str, source_enc: str, target_enc: str, output_path: str, verbose: int = 0) -> None:
"""Convert a single file from source_enc to target_enc."""
with open(input_path, 'r', encoding=source_enc) as f:
content = f.read()
if verbose > 0:
orig_size = len(content.encode(source_enc))
new_size = len(content.encode(target_enc))
print(f" Content length: {len(content)} chars | Orig bytes: {orig_size} | New bytes: {new_size}")
with open(output_path, 'w', encoding=target_enc) as f:
f.write(content)
print(f"✓ Converted: {input_path} -> {output_path}")
def main():
parser = argparse.ArgumentParser(
description="Convert text file(s) from one encoding to another.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s file.txt --target utf-8
%(prog)s *.txt --source iso-8859-1 --target utf-8 -o ./utf8/
%(prog)s doc.txt --detect-source --target utf-8 -vv
"""
)
parser.add_argument(
'inputs', nargs='+',
help="Input file(s) to convert"
)
parser.add_argument(
'--source', '-s', default='utf-8',
help="Source encoding (default: utf-8)"
)
parser.add_argument(
'--target', '-t', required=True,
help="Target encoding (required)"
)
parser.add_argument(
'--output-dir', '-o',
help="Output directory (default: same as input dir)"
)
parser.add_argument(
'--detect-source', action='store_true',
help="Auto-detect source encoding using chardet (requires: pip install chardet)"
)
parser.add_argument(
'--overwrite', action='store_true',
help="Overwrite existing output files"
)
parser.add_argument(
'--dry-run', action='store_true',
help="Show what would be done without converting"
)
parser.add_argument(
'-v', '--verbose', action='count', default=0,
help="Verbose output (-v: basic, -vv: detailed)"
)
args = parser.parse_args()
if args.detect_source and args.source != 'utf-8':
print("Warning: --source arg ignored when --detect-source is used", file=sys.stderr)
target_suffix = args.target.lower().replace('-', '_')
processed = 0
errors = 0
for input_arg in args.inputs:
input_path = Path(input_arg)
if not input_path.is_file():
print(f"✗ Not a file or not found: {input_path}", file=sys.stderr)
errors += 1
continue
# Determine source encoding
if args.detect_source:
try:
source_enc = detect_encoding(input_path)
if args.verbose > 0:
print(f"Detected source encoding: {source_enc}")
except Exception as e:
print(f"✗ Detection failed for {input_path}: {e}", file=sys.stderr)
errors += 1
continue
else:
source_enc = args.source
# Compute output path
stem = input_path.stem
suffix = input_path.suffix
output_name = f"{stem}_{target_suffix}{suffix}"
if args.output_dir:
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / output_name
else:
output_path = input_path.parent / output_name
if output_path.exists() and not args.overwrite:
print(f"✗ Output exists (use --overwrite): {output_path}", file=sys.stderr)
errors += 1
continue
if args.dry_run:
print(f"DRY-RUN: {input_path} ({source_enc}) -> {output_path} ({args.target})")
processed += 1
continue
try:
convert_file(str(input_path), source_enc, args.target, str(output_path), args.verbose)
processed += 1
except UnicodeDecodeError as e:
print(f"✗ Decode error ({source_enc}) in {input_path}: {e}", file=sys.stderr)
errors += 1
except UnicodeEncodeError as e:
print(f"✗ Encode error ({args.target}) for {input_path}: {e}", file=sys.stderr)
errors += 1
except Exception as e:
print(f"✗ Unexpected error for {input_path}: {e}", file=sys.stderr)
errors += 1
print(f"\nSummary: {processed} processed, {errors} errors", file=sys.stderr)
sys.exit(1 if errors > 0 else 0)
if __name__ == '__main__':
main()
Tested on Python 3.8+. Handles large files efficiently (reads all into memory).