Remove empty rows in python. Remove empty rows in python.
When processing empty rows in python, some problems are often encountered. The summary is as follows:
1. If the blank line is only a line break, use = '\ n' or len (line) = line. count (' \ n ')
2. When there are multiple spaces + line breaks. There are several Processing Methods: ① split; ② regular expression '^ \ n' (NO); ③ if eachLine [:-1]. strip ()
Expand:
For example, if the file is filtered out, all rows of a file are displayed, and the rows starting with the pound sign (#) are ignored.
①
1 f=open('test.txt ', 'R') 2 for eachLine in f: 3 if not eachLine. split (): # whether space4 print eachLine, 5 elif eachLine. strip () [0]! = '#': 6 print eachLine, 7 8 f. close ()
③
1 f=open('test.txt ', 'R') 2 for eachLine in f: 3 if not eachLine [:-1]. strip (): # whether space4 print eachLine, 5 elif eachLine. strip () [0]! = '#': 6 print eachLine, 7 8 f. close ()
Both methods can be judged,
Reading the same number of rows of letters from the same computer takes 8.4 s for the first method and 1.6 s for the third method. From the perspective of experiments, the third method is relatively better.
However, [:-1]. strip () has better performance and needs further study.