简体   繁体   中英

Reading a file using python 3.x not skipping blank lines?

I'm trying to read a file and simply skip the blank lines. from some reason it doesn't really skip the empty lines. what am i doing wrong?:

ourFile = 'File.txt'
with open(ourFile) as fp:
    for tmpLine in fp:
        currentLine = tmpLine.strip()
        if currentLine != '\n' and currentLine != '\r\n':
             print(currentLine)

strip() strips any whitespace, including line breaks '\\n' or carriage returns '\\r' :

currentLine = tmpLine.strip()
if currentLine != '':
    print(currentLine)
# or simply:
if currentLine:
    print(currentLine)

For a rough orientation which characters get stripped by default, you can look at string.whitespace :

import string
string.whitespace
# '\t\n\x0b\x0c\r '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM