2

I am using csv.reader to read file but it giving me whole file.

file_data = self.request.get('file_in');
file_Reader = csv.reader( file_data );
for fields in file_Reader:

I want one line at a time and separate data from that line.

ex: filedata = name,sal,dept
               x,12000,it
o\p=
name
sal
dept
.
.
.

4 Answers 4

3

This

>>> import csv
>>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|')
>>> for row in spamReader:
...     print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

Was taken from the manual

Hope that helps...

Sign up to request clarification or add additional context in comments.

4 Comments

it is giving me whole file in a single line
My point is that by the time the code reaches the print line, row should be a list of the items in a specific row of your csv. Is this not what you're seeing?
This prints the values of the row. How do I say value1=1stvalue,value2=2ndvalue, etc working code?
Each row is a list, so if you wanted the first value, you would use row[0] to access that.
2

It looks like you are trying to pass a string of data directly to csv.reader(). It's expecting an iterable object like a list or filehandle. The docs for the csv module mention this. So you probably want to split the string along newlines before passing it to csv.reader.

import csv
file_data = self.request.get('file_in')
file_data_list = file_data.split('\n')
file_Reader = csv.reader(file_data_list)
for fields in file_Reader:
    print row

Hope that helps.

1 Comment

This just prints the row. How do we get each individual value out, one for one? Working code example?
1

Why not do it manually?

for line in fd:
        foo, bar, baz = line.split(";")

2 Comments

That wouldn't handle things like quotes correctly though, would it - which would be needed if the data in the csv could, in itself, contain commas...
+1 for the hint. This is a common speed-vs-comfort trade-off.
1

Usually the delimiter used is ",", I have mapped the data into x,y variables

import csv
x = []
y=  []
with open('FileName.csv','r') as csvfile:
    plot=csv.reader(csvfile,delimiter=',')
for row in plot:
    x.append(int(row[0])) 
    y.append(int(row[1]))

plt.bar(x,y,label='name')

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.