开发者

How to get data from CSV file in Python?

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
          开发者_StackOverflow     x,12000,it
o\p=
name
sal
dept
.
.
.


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.


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...


Why not do it manually?

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


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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜