0

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.

2

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

1

read the row and then use split

f=open(filename,'r')
fields=f.readline().split(',')

now fields[i] is the i-th field

2 Comments

This will not work on a "real" csv file that may have quoted fields.
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.
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.