3 ms·
I've found pathlib (in Python's standard library) very convenient for tasks like these. I think the entire second example could just be: lines = Path("in.t
by Ukv 2y ago
I've found pathlib (in Python's standard library) very convenient for tasks like these. I think the entire second example could just be:
lines = Path("in.txt").read_text().splitlines()
trimmed = "\n".join(lines[1: -1])
Path("out.txt").write_text(trimmed)
Granted the example in the article has advantages (like not loading the full file at once) if you want something more permanent, opposed to a quick script ran once/occasionally.
- mbb70 2y agoYour script requires over 3x the entire file in memory (text, lines, "\n".join(lines)) whereas the posts rust/python are line by line, so support arbitrarily large files.
- Ukv 2y agoIf you are dealing with many-gigabyte files or a performance-critical pipeline then yeah, you'd want to do it line-by-line. My example is just a quick and dirty script, or REPL input, without any of the boilerplate - which I think is an area Python excels in.