mary mary -4 years ago 169
Python Question

Reading .csv in Python without looping through the whole file?

The only way I've seen Python's csv.reader used is in a for loop, which goes through the whole file without saving past values of the read in variables. I only need to work with 2 consecutive lines of the (enormous) file at a time. Using the csv.reader for loop, I only have 1 line at a time.

Is there a way to use Python's csv module for taking in only one line of a csv file without having to finish reading the file to the end?

I need to set variables to the values in the first line, set a second set of variables to the values of the next line, use the two sets of variables simultaneously for computations, then overwrite the first set of variables with the second set, and read a new line to overwrite the second set.

Answer Source

There's nothing forcing you to use the reader in a loop. Just read the first line, then read the second line.

import csv
r = csv.reader(open("data.csv"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download