Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to iterate through a file on something other than newlines

Tags:

python

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?

like image 642
Illusionist Avatar asked Feb 24 '15 15:02

Illusionist


People also ask

How do you iterate a text file line by line in Python?

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.

How do you go to the next line while reading a file in Python?

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.


1 Answers

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(","):
like image 195
Padraic Cunningham Avatar answered Sep 20 '22 06:09

Padraic Cunningham