Is it possible to read in a CSV file in Python one field at a time rather than an entire row? I have an input that is a single row with a large amount of comma separated values. I need to progress through the file one value at a time.
-
3Couldn't you just read a row and then iterate through it, field by field?pushkin– pushkin2015-10-21 21:48:34 +00:00Commented Oct 21, 2015 at 21:48
-
1Possible duplicate of Read Specific Columns from csv file with Python csvsmac89– smac892015-10-21 21:50:38 +00:00Commented Oct 21, 2015 at 21:50
Add a comment
|
4 Answers
You may get the csv data in the List and then iterate the list:
import csv
f1="filename.csv"
with open(f1, 'rU') as csvfile1:
csvreader1 = csv.reader(csvfile1)
for line1 in csvreader1:
print "List of Values from File=", line1
#Iterate List to get seperate items.
for idx,item in enumerate(line1):
print idx , ": ", item
Comments
read the row and then use split
f=open(filename,'r')
fields=f.readline().split(',')
now fields[i] is the i-th field
Assuming that you're using a csv reader my_reader ...
row_stream = (row for row in my_reader)
field_stream = (field for field in row)
for field in field_stream:
....
This gives you a stream of fields instead of a sequence of csv rows. If you replace the "for" expression with a generator comprehension, you can continue the pipeline.