I have a huge input .txt file of this form:
0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0
and I want to delete all empty lines in order to create a new output .txt file like this:
0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0
I tried doing it with grep:
grep -v '^$' test1.txt > test2.txt
but I get "SyntaxError: invalid syntax"
When I do it with pandas as someone suggests, I get different number of columns and some integers are converted into floats: e.g.: 1.0 instead of 1
When I do it as inspectorG4dget suggests (see below), it works nice, with only 1 problem: the last line is not printed completely:
with open('path/to/file') as infile, open('output.txt', 'w') as outfile:
for line in infile:
if not line.strip(): continue # skip the empty line
outfile.write(line) # non-empty line. Write it to output
It must be something with my file then...
I've already addressed similar posts like these below (and others), but they are not working in my case, mainly due to the reasons explained above
How to delete all blank lines in the file with the help of python?
one liner for removing blank lines from a file in python?
In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box. Click the Replace All button to replace all blank lines.
The d command in sed can be used to delete the empty lines in a file.
This is how I would do it:
with open('path/to/file') as infile, open('output.txt', 'w') as outfile:
for line in infile:
if not line.strip(): continue # skip the empty line
outfile.write(line) # non-empty line. Write it to output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With