簡體   English   中英

為什么在“.readlines()”之后“for line in f”不打印任何內容?

[英]Why doesn't `for line in f` print anything after `.readlines()`?

with open("data.txt", "r+") as f:
    if f.readlines() == []:
        f.write(input("Enter your name : "))
        f.write("\n" + input("Enter your name_roll no (javets_6890) : "))
        f.write("\n" + input("Enter the password for your mail id : "))
        f.write("\n" + input("Enter your roll number : "))
        f.write("\n" + input("Enter your admission number : "))
    for line in f:
        print(line)

我試圖打印包含一些文本的“data.txt”文件的行,但是當我執行此代碼時,沒有打印出任何內容。

這是因為.readlines()消耗了文件緩沖區,所以當你迭代for line in f ,文件指針已經在文件的末尾。 您可以檢查.tell()以查看文件指針不再位於文件的開頭。

with open("data.txt", "r+") as f:
    print(f.tell())  # Prints 0
    if f.readlines() == []:
        # ... your code ...
    print(f.tell())  # Prints total bytes written in file

事實上,文檔提到他們都做同樣的事情:

請注意,已經可以使用for line in file: ...不調用file.readlines()情況下迭代文件對象。

典型的解決方案是使用.seek(0)將文件指針倒回到文件的開頭(如為什么我第二次在同一個文件上運行“readlines”沒有返回任何內容?

但是從您的用例來看,我建議不要使用readlines()來檢查文件是否為空。 相反,使用.tell().seek()來檢查文件是否為空。

from io import SEEK_END

with open("data.txt", "r+") as f:
    # Move the file pointer to the end of the file
    f.seek(0, SEEK_END)
    if f.tell() == 0:
        # The file pointer is still at the start of the file
        # This means the file is empty
        f.write(input("Enter your name : "))
        f.write("\n" + input("Enter your name_roll no (javets_6890) : "))
        f.write("\n" + input("Enter the password for your mail id : "))
        f.write("\n" + input("Enter your roll number : "))
        f.write("\n" + input("Enter your admission number : "))
    # Rewind file pointer back to the start of the file
    f.seek(0)
    for line in f:
        print(line)

我認為這更好,因為您不必兩次閱讀文件的內容。

暫無
暫無

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

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