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.
Asked
Active
Viewed 691 times
0
-
3Couldn't you just read a row and then iterate through it, field by field? – pushkin Oct 21 '15 at 21:48
-
1Possible duplicate of [Read Specific Columns from csv file with Python csv](http://stackoverflow.com/questions/16503560/read-specific-columns-from-csv-file-with-python-csv) – smac89 Oct 21 '15 at 21:50
4 Answers
2
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

H. U.
- 627
- 1
- 10
- 25
1
read the row and then use split
f=open(filename,'r')
fields=f.readline().split(',')
now fields[i] is the i-th field

OMRY VOLK
- 1,429
- 11
- 24
-
1
-
This will work for my scenario. My input will not be an actual csv file. I was just using one to mimic the data I will receive from a piece of measurement equipment. – Xaples Oct 21 '15 at 22:05
0
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.

Prune
- 76,765
- 14
- 60
- 81
0
Answer from user4421975 works well for me. I also found that this works:
f=open(filename,'r')
reader = csv.reader(f)
row = reader.next()
Now row[i] has the different fields.

Xaples
- 13
- 6