如何在 Python 中从 CSV 文件中获取数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2409330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:35:43  来源:igfitidea点击:

How to get data from CSV file in Python?

python

提问by Rahul99

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

我正在使用 csv.reader 读取文件,但它给了我整个文件。

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

采纳答案by razzmataz

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 modulemention this. So you probably want to split the string along newlines before passing it to csv.reader.

看起来您正试图将一串数据直接传递给 csv.reader()。它期待一个可迭代对象,如列表或文件句柄。csv 模块的文档提到了这一点。因此,您可能希望在将字符串传递给 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.

希望有帮助。

回答by Martin Milan

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

希望有帮助...

回答by Gowtham Prasath

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

通常使用的分隔符是“,”,我已经将数据映射到 x,y 变量中

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

回答by Philip

Why not do it manually?

为什么不手动做呢?

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