Heim  >  Fragen und Antworten  >  Hauptteil

python readline()逐行读,怎么判断已到末尾?

天蓬老师天蓬老师2711 Tage vor493

Antworte allen(5)Ich werde antworten

  • PHP中文网

    PHP中文网2017-04-18 09:34:08

    两种方法:

    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)

    Antwort
    0
  • 阿神

    阿神2017-04-18 09:34:08

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

    Antwort
    0
  • 黄舟

    黄舟2017-04-18 09:34:08

    for ... in ...:

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

    Antwort
    0
  • 黄舟

    黄舟2017-04-18 09:34:08

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

    while True:
        line=f.readline()
        if line:
            print (line)
        else:
            break

    Antwort
    0
  • 黄舟

    黄舟2017-04-18 09:34:08

    • 你說的沒錯, readlines 是絕對不要使用的!

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

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

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


    我回答過的問題: Python-QA

    Antwort
    0
  • StornierenAntwort