Need help understanding why certain things are happening with readlines()

Hey everyone I am learning about the readlines() function & had 2 questions regarding this.

1: I know that if you have opened a file, and are trying to read the lines using a for loop, you don’t actually need to use .readlines() after the file name in the for loop. Why do some people still use the .readlines() function after the file name in the for loop if it doesn’t make a difference?

2: This question is related to the first.

When I run this code:

test_file = open(“Test.txt”, “r”)

for line in test_file:
print(line)

test_file.close()

It prints the lines of my file from top to bottom. But when I run this code

test_file = open(“Test.txt”, “r”)

test_file.readlines()

for line in test_file:
print(line)

test_file.close()

It no longer works, and prints nothing. Why does adding test_file.readlines() cause it to print nothing?

I know this is a really trivial question but I think understanding these glitches and the logic/rules behind them will solidify my knowledge of the syntax. I really appreciate your time and assistance if you made it this far down the post.

Thanks!

It’s because test_file is a file object and the use of readlines returns every line in the file (effectively iterating through every byte) leaving you at the end of the file. Attempting to continue iteration at that point will raise StopIteration so your for loop finishes instantly and nothing gets printed.

If you just wanted a list of ‘lines’ in the file then assign the output of test_file.readlines() to a name as that is what it returns.

If you want a bit more knowledge of how Python deals with files then check the following docs (especially the details of using with to neatly deal with opening and closing the file)-

If you have an example of the file object being iterated though and then have the .readlines method called then please add it as I’m not sure what order you mean.

2 Likes

Thanks so much!!! <3