Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

blank lines in file after sorting content of a text file in python

Tags:

python

I have this small script that sorts the content of a text file

# The built-in function `open` opens a file and returns a file object.

# Read mode opens a file for reading only.
try:
    f = open("tracks.txt", "r")


    try:
        # Read the entire contents of a file at once.
       # string = f.read() 
        # OR read one line at a time.
        #line = f.readline()
        # OR read all the lines into a list.
        lines = f.readlines()
        lines.sort()
        f.close()
        f = open('tracks.txt', 'w')
        f.writelines(lines) # Write a sequence of strings to a file
    finally:
        f.close()
except IOError:
    pass

the only problem is that the text is displayed at the bottom of the text file everytime it's sortened...

I assume it also sorts the blank lines...anybody knows why?

and maybe can you suggest some tips on how to avoid this happening?

thanks in advance

like image 838
rabidmachine9 Avatar asked Jun 09 '10 00:06

rabidmachine9


People also ask

Why is Python printing blank lines?

This occurs because, according to the Python Documentation: The default value of the end parameter of the built-in print function is \n , so a new line character is appended to the string.

How do I remove blank lines in a text file?

Open TextPad and the file you want to edit. Click Search and then Replace. 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.

Why are there blank lines at the end of a file?

The empty line in the end of file appears so that standard reading from the input stream will know when to terminate the read, usually returns EOF to indicate that you have reached the end. The majority of languages can handle the EOF marker.


1 Answers

An "empty" line read from a text file is represented in Python by a string containing only a newline ("\n"). You may also want to avoid lines whose "data" consists only of spaces, tabs, etc ("whitespace"). The str.strip() method lets you detect both cases (a newline is whitespace).

f = open("tracks.txt", "r")
# omit empty lines and lines containing only whitespace
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
# now write the output file
like image 95
John Machin Avatar answered Nov 15 '22 12:11

John Machin