简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM