Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f.readlines() won't return any values

So I was reading over the Python Documentation/Tutorial, specifically I was looking at the Input/Output with files. This is what the tutorial says will return whatevers in the file:

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''

I put the same thing in my .py and it didn't return any exceptions or issues, but it didn't return any values, either. This is my code:

f = open('test.txt')

f.readlines()

Unless I use the variables and a print, the program will not return anything thats in the file. Heres my files contents:

Hello This Is Test
For Loops In Files
Flying Away
A Bird also Flies
Wow

Any ideas as to why this isn't working? I think its my interpreter, as I am using SublimeREPL, but it hasn't been doing anything weird before then so I am not too sure. Also, when I try running it in my Python console, it gives me an error, then just closes the console so I can't even see the error. Pretty counter-productive.

Just to clarify, my issue is not the for loop, the for loop already worked fine from before. The issue is that f.readlines() does not return any lines, even though the documentation says it should return the next line. I will take the for loop out of my code to clarify. Also, sorry if I am mixing up f.readline() and f.readlines(), but they both don't work, anyway.

like image 714
said Avatar asked Mar 25 '26 07:03

said


1 Answers

I've figured out an answer to a very similar issue in case someone comes here looking. So in Python if you have ran code of readline() prior to readlines() then it has already iterated through those lines.

Try exiting out and ONLY typing readlines() for a file and it will make the full list for you.

like image 181
Colin Skinner Avatar answered Mar 27 '26 20:03

Colin Skinner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!