python readline()逐行读,怎么判断已到末尾?
天蓬老师
天蓬老师 2017-04-18 09:32:08
0
5
491
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

Antworte allen(5)
Ty80

两种方法:

1. for ... in ...

with open("file") as fh:
    for line in fh:
        print(line.strip())

2. while fh.readline():

with open("file") as fh:
    line = fh.readline()
    while line:
        print(line.strip())
        line = fh.readline()

最简洁优雅又高效的自然是第一种, 如果题主非要用readline(), 则可以使用第二种, while循环, 读到最后一行没有内容会退出循环, 中间有空行不要紧, 空行不等于结尾(\n != EOF)

阿神

http://www.jb51.net/article/5...

黄舟

for ... in ...:

with open('filename') as fp:
    for line in fp:
        # do something
黄舟

with open('filename','r') as f:

while True:
    line=f.readline()
    if line:
        print (line)
    else:
        break
黄舟
  • 你說的沒錯, readlines 是絕對不要使用的!

    • 請參考 Python 如何實現並行查找關鍵字所在的行 和 Never call readlines() on a file

  • 一般的文件讀取(從頭到尾讀一遍), 請使用 for line in file 來迭代文件, 簡潔又不容易出錯

  • readline 可能會用在當讀取順序比較複雜的時候


我回答過的問題: Python-QA

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!