Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete empty lines from a .txt file [duplicate]

Tags:

python

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?

like image 930
Lucas Avatar asked Jun 07 '16 15:06

Lucas


People also ask

How do I remove blank lines in a text file?

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.

Which command will delete all blank lines found in old text?

The d command in sed can be used to delete the empty lines in a file.


1 Answers

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
like image 120
inspectorG4dget Avatar answered Sep 18 '22 08:09

inspectorG4dget