Skaperen you should show some effort when posting these requests 💤
Windows dos bad guessing:
Here my take on this and i use Typer for CLI application.
Compare to see that it work the same.
(May-13-2024, 08:32 AM)Gribouillis Wrote: Here is a complete script (for a single file argument). Assumes utf8 encoding of the target fileGood,to make more robust as it fail sometime on files with Unicodes on Windows.
Windows dos bad guessing:
Error:UnicodeDecodeError: 'charmap' codec can't decode byte .....
with open(arg.file, encoding='utf-8', errors='ignore') as infile: print(f'==> (head) {arg.file} <==')
Here my take on this and i use Typer for CLI application.
import typer from collections import deque app = typer.Typer() @app.command() def headtail(filename: str, head: int = 5, tail: int = 5): tail_deque = deque(maxlen=tail) head_list = [] total_lines = 0 try: with open(filename, encoding='utf-8', errors='ignore') as file: for i, line in enumerate(file): if i < head: head_list.append(line) tail_deque.append(line) total_lines += 1 if total_lines <= head + tail: for line in head_list: print(line, end='') else: for line in head_list: print(line, end='') if tail > 0: print("...........") for line in tail_deque: print(line, end='') except FileNotFoundError: typer.echo(f"Error: The file '{filename}' does not exist.", err=True) except Exception as e: typer.echo(f"An error occurred: {e}", err=True) if __name__ == "__main__": app()
Compare to see that it work the same.
Output:G:\div_code\reader_env
λ python head_tail_grib.py -n 2 -m 7 contry.txt
==> (head) contry.txt <==
Tokyo;35.6897
Jakarta;-6.1750
==> (tail) contry.txt <==
Nanyang;32.9987
Hangzhou;30.2500
Foshan;23.0292
Nagoya;35.1833
Taipei;25.0375
Tongshan;34.2610
Dhanbād;23.7998
G:\div_code\reader_env
λ python head_tail.py contry.txt --head 2 --tail 7
Tokyo;35.6897
Jakarta;-6.1750
............
Nanyang;32.9987
Hangzhou;30.2500
Foshan;23.0292
Nagoya;35.1833
Taipei;25.0375
Tongshan;34.2610
Dhanbād;23.7998
G:\div_code\reader_env
Update: had two "with open" need only one.