The line.strip()
will only strip that line, but that does not mean that if the line is empty the line somehow will disappear. Furthermore you never really store the (processed) line in (another) file.
You can process the file and write the result to a target.txt
file with:
with open('path/to/file.txt', 'r') as f:
with open('path/to/target.txt', 'w') as w:
for line in f:
if line.strip():
w.write(line)
If you want to strip non-empty lines as well, so remove leading and trailing spaces from all lines, you can use the stripped variant:
with open('path/to/file.txt', 'r') as f:
with open('path/to/target.txt', 'w') as w:
for line in f:
line = line.strip()
if line:
w.write(line)
w.write('\n')
This program will read the file line-by-line, which is often better for huge files, since loading a huge file in memory, can result in memory problems.
Furthermore it is often better to store the result in another file. If the machine crashes while processing (for example due to power failure), then you still have the original file. Most Linux commands are designed to write to another file. Such that later, when the operation is done, you move the target to the original file.