bench_mixed / clean.py
Prummn's picture
Add files using upload-large-folder tool
44e0257 verified
raw
history blame
1.54 kB
#!/usr/bin/env python3
# clean_empty_lines.py
import argparse
from pathlib import Path
def clean_txt_file(input_path: Path, output_path: Path | None = None):
if not input_path.exists():
raise FileNotFoundError(f"File not found: {input_path}")
if input_path.suffix.lower() != ".txt":
raise ValueError(f"Input file must be a .txt file: {input_path}")
with input_path.open("r", encoding="utf-8") as f:
lines = f.readlines()
cleaned_lines = [line for line in lines if line.strip()]
target_path = output_path if output_path is not None else input_path
with target_path.open("w", encoding="utf-8") as f:
f.writelines(cleaned_lines)
print(f"Done: {input_path}")
print(f"Original lines: {len(lines)}")
print(f"Cleaned lines: {len(cleaned_lines)}")
print(f"Removed lines: {len(lines) - len(cleaned_lines)}")
print(f"Saved to: {target_path}")
def main():
parser = argparse.ArgumentParser(
description="Remove empty lines from a txt file."
)
parser.add_argument(
"input",
type=str,
help="Path to input txt file"
)
parser.add_argument(
"-o",
"--output",
type=str,
default=None,
help="Path to output txt file. If omitted, overwrite the input file."
)
args = parser.parse_args()
input_path = Path(args.input)
output_path = Path(args.output) if args.output else None
clean_txt_file(input_path, output_path)
if __name__ == "__main__":
main()