In Python, after
fh = open('file.txt')
one may do the following to iterate over lines:
for l in fh: pass
Then why do we have fh.readlines()
?
The readlines() method returns a list containing each line in the file as a list item. Use the hint parameter to limit the number of lines returned.
To iterate through lines in a file using Python, you can loop over each line in a file with a simple for loop. When reading files, the ability to read files sequentially line by line can be very useful. Reading text from a file is easy with the Python open() function.
The readlines method returns the contents of the entire file as a list of strings, where each item in the list represents one line of the file. It is also possible to read the entire file into a single string with read .
I would imagine that it's from before files were iterators and is maintained for backwards compatibility. Even for a one-liner, it's totally1 fairly redundant as list(fh)
will do the same thing in a more intuitive way. That also gives you the freedom to do set(fh)
, tuple(fh)
, etc.
1 See John La Rooy's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With