簡體   English   中英

使用python 3.x讀取文件不會跳過空行?

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

我正在嘗試讀取文件,只是跳過空白行。 由於某種原因,它並沒有真正跳過空白行。 我究竟做錯了什么?:

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()去除所有空格,包括換行符'\\n'或回車符'\\r'

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

對於默認情況下會去除字符的粗略方向,您可以查看string.whitespace

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM