简体   繁体   中英

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)

I am trying to print the lines of the "data.txt" file containing some text, but when I execute this code, nothing gets printed out.

It is because .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() to see that the file pointer is not anymore at the start of the file.

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

In fact, the docs mentions that they both do the same thing:

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

The typical solution is to use .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? )

But from your use case, I suggest not using readlines() to check if the file is empty. Instead, use a combination of .tell() and .seek() to check if the file is empty.

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)

I think this is better since you don't have to read the contents of the file twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM