为什么 `for line in f` 在 `.readlines()` 之后不打印任何内容?

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() consumes the file buffer, so by the time you iterate for line in f, the file pointer is already at the end of the file. You can check with .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

事实上,文档提到它们都做同样的事情:

Note that it’s already possible to iterate on file objects using for line in file: ... without calling file.readlines().

典型的解决方案是使用.seek(0) to rewind the file pointer back to the start of the file (as shown in Why the second time I run “readlines” on the same file nothing is returned?)

但是根据您的用例,我建议不要 使用readlines() 检查文件是否为空。相反,使用 .tell() and .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)

我认为这样更好,因为您不必两次读取文件的内容。