File size: 1,535 Bytes
44e0257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/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()