To iterate a file by lines, one can do -
for line in f:
(where f is the file iterator).
I want to iterate the file by blocks delimited by commas, instead of blocks delimited by newlines. I can read all lines and then split the string on commas, but whats the pythonic way to do this?
Method 1: Read a File Line by Line using readlines() This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline '\n' character using strip() function. Example: Python3.
Python file method next() is used when a file is used as an iterator, typically in a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.
Iterate over the split as you go then you don't need to store all the lines:
for line in f:
for lines in line.split(","):
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