如何使用 Python 读取和写入 CSV 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41585078/
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
How do I read and write CSV files with Python?
提问by Martin Thoma
I have a file example.csv
with the contents
我有一个example.csv
包含内容的文件
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3
How do I read this example.csv
with Python?
我如何example.csv
用 Python阅读这个?
Similarly, if I have
同样,如果我有
data = [(1, "A towel,", 1.0),
(42, " it says, ", 2.0),
(1337, "is about the most ", -1),
(0, "massively useful thing ", 123),
(-2, "an interstellar hitchhiker can have.", 3)]
How do I write data
to a CSV file with Python?
如何data
使用 Python写入CSV 文件?
回答by Martin Thoma
Here are some minimal complete examples how to read CSV files and how to write CSV files with Python.
以下是一些如何读取 CSV 文件以及如何使用 Python 编写 CSV 文件的最小完整示例。
Python 3: Reading a CSV file
Python 3:读取 CSV 文件
Pure Python
纯Python
import csv
# Define data
data = [
(1, "A towel,", 1.0),
(42, " it says, ", 2.0),
(1337, "is about the most ", -1),
(0, "massively useful thing ", 123),
(-2, "an interstellar hitchhiker can have.", 3),
]
# Write CSV file
with open("test.csv", "wt") as fp:
writer = csv.writer(fp, delimiter=",")
# writer.writerow(["your", "header", "foo"]) # write header
writer.writerows(data)
# Read CSV file
with open("test.csv") as fp:
reader = csv.reader(fp, delimiter=",", quotechar='"')
# next(reader, None) # skip the headers
data_read = [row for row in reader]
print(data_read)
After that, the contents of data_read
are
之后的内容data_read
是
[['1', 'A towel,', '1.0'],
['42', ' it says, ', '2.0'],
['1337', 'is about the most ', '-1'],
['0', 'massively useful thing ', '123'],
['-2', 'an interstellar hitchhiker can have.', '3']]
Please note that CSV reads only strings. You need to convert to the column types manually.
请注意,CSV 仅读取字符串。您需要手动转换为列类型。
A Python 2+3 version was here before (link), but Python 2 support is dropped. Removing the Python 2 stuff massively simplified this answer.
之前有一个 Python 2+3 版本(链接),但不再支持 Python 2。删除 Python 2 的东西大大简化了这个答案。
Related
有关的
- How do I write data into csv format as string (not file)?
- How can I use io.StringIO() with the csv module?: This is interesting if you want to serve a CSV on-the-fly with Flask, without actually storing the CSV on the server.
- 如何将数据作为字符串(不是文件)写入 csv 格式?
- 如何将 io.StringIO() 与 csv 模块一起使用?:如果您想使用 Flask 即时提供 CSV 文件,而不实际将 CSV 文件存储在服务器上,这会很有趣。
mpu
处理器
Have a look at my utility package mpu
for a super simple and easy to remember one:
看看我的实用程序包mpu
,里面有一个超级简单易记的包:
import mpu.io
data = mpu.io.read('example.csv', delimiter=',', quotechar='"', skiprows=None)
mpu.io.write('example.csv', data)
Pandas
熊猫
import pandas as pd
# Read the CSV into a pandas data frame (df)
# With a df you can do many things
# most important: visualize data with Seaborn
df = pd.read_csv('myfile.csv', sep=',')
print(df)
# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]
# or export it as a list of dicts
dicts = df.to_dict().values()
See read_csv
docsfor more information. Please note that pandas automatically infers if there is a header line, but you can set it manually, too.
有关更多信息,请参阅read_csv
文档。请注意,pandas 会自动推断是否有标题行,但您也可以手动设置。
If you haven't heard of Seaborn, I recommend having a look at it.
如果你还没有听说过Seaborn,我建议你看看它。
Other
其他
Reading CSV files is supported by a bunch of other libraries, for example:
许多其他库都支持读取 CSV 文件,例如:
Created CSV file
创建的 CSV 文件
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3
Common file endings
常见的文件结尾
.csv
.csv
Working with the data
处理数据
After reading the CSV file to a list of tuples / dicts or a Pandas dataframe, it is simply working with this kind of data. Nothing CSV specific.
在将 CSV 文件读取到元组/字典列表或 Pandas 数据框后,它只是处理这种数据。没有具体的 CSV 文件。
Alternatives
备择方案
- JSON: Nice for writing human-readable data; VERY commonly used (read & write)
- CSV: Super simple format (read & write)
- YAML: Nice to read, similar to JSON (read & write)
- pickle: A Python serialization format (read & write)
- MessagePack(Python package): More compact representation (read & write)
- HDF5(Python package): Nice for matrices (read & write)
- XML: exists too *sigh* (read& write)
- JSON:非常适合编写人类可读的数据;非常常用(读写)
- CSV:超级简单的格式(读写)
- YAML: 好读,类似于 JSON ( read & write)
- pickle:一种 Python 序列化格式(读写)
- MessagePack(Python 包):更紧凑的表示(读写)
- HDF5(Python 包):非常适合矩阵(读写)
- XML: 也存在 *sigh* ( read& write)
For your application, the following might be important:
对于您的应用程序,以下内容可能很重要:
- Support by other programming languages
- Reading / writing performance
- Compactness (file size)
- 其他编程语言的支持
- 读/写性能
- 紧凑性(文件大小)
See also: Comparison of data serialization formats
另请参阅:数据序列化格式的比较
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
如果您正在寻找一种制作配置文件的方法,您可能需要阅读我的短文Python 中的配置文件
回答by Syed Abdul Rehman
Writing a CSV file
写入 CSV 文件
First you need to import csv
首先你需要导入csv
For eg:
例如:
import csv
with open('eggs.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
回答by Siddharth Kumar Shukla
import csv
with open(fileLocation+'example.csv',newline='') as File: #the csv file is stored in a File object
reader=csv.reader(File) #csv.reader is used to read a file
for row in reader:
print(row)
回答by prasanna kumar
To read a csv file using Pandas
使用 Pandas 读取 csv 文件
use pd.read_csv("D:\sample.csv")
using only python :
fopen=open("D:\sample.csv","r")
print(fopen.read())
To create and write into a csv file
创建并写入 csv 文件
The below example demonstrate creating and writing a csv file. to make a dynamic file writer we need to import a package import csv, then need to create an instance of the file with file reference Ex:
下面的示例演示了创建和写入 csv 文件。要制作动态文件编写器,我们需要导入一个包 import csv,然后需要使用文件引用创建一个文件实例,例如:
with open("D:\sample.csv","w",newline="") as file_writer
Here if the file does not exist with the mentioned file directory then python will create a same file in the specified directory, and w
represents write, if you want to read a file then replace w
with r
or to append to existing file then a
.
这里如果文件不存在于提到的文件目录中,那么python将在指定目录中创建一个相同的文件,并w
表示写入,如果要读取文件则替换w
为r
或附加到现有文件然后a
。
newline=""
specifies that it removes an extra empty row for every time you create row so to eliminate empty row we use newline=""
, create some field names(column names) using list like:
newline=""
指定它每次创建行时都会删除一个额外的空行,以便消除我们使用的空行newline=""
,使用列表创建一些字段名称(列名称),例如:
fields=["Names","Age","Class"]
Then apply to writer instance like:
然后适用于作家实例,如:
writer=csv.DictWriter(file_writer,fieldnames=fields)
Here using Dictionary writer and assigning column names, to write column names to csv we use writer.writeheader()
and to write values we use writer.writerow({"Names":"John","Age":20,"Class":"12A"})
,while writing file values must be passed using dictionary method , here the key is column name and value is your respective key value.
这里使用字典编写器并分配列名,将列名写入我们使用的 csvwriter.writeheader()
并写入我们使用的值writer.writerow({"Names":"John","Age":20,"Class":"12A"})
,而写入文件值必须使用字典方法传递,这里的键是列名,值是您各自的键值。
Import csv:
导入.csv:
with open("D:\sample.csv","w",newline="") as file_writer:
fields=["Names","Age","Class"]
writer=csv.DictWriter(file_writer,fieldnames=fields)
writer.writeheader()
writer.writerow({"Names":"John","Age":21,"Class":"12A"})