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

后端 未结 3 1204
北恋
北恋 2020-12-31 11:41

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 fi         


        
3条回答
  •  萌比男神i
    2020-12-31 12:04

    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
    

提交回复
热议问题