我有一个包含内容的文件 example.csv
I have a file example.csv
with the contents
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
如何使用 Python 读取此 example.csv
?
How do I read this example.csv
with Python?
同样,如果我有
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)]
如何使用 Python 将 data
写入 CSV 文件?
How do I write data
to a CSV file with Python?
这里有一些最小的完整示例如何读取 CSV 文件以及如何使用 Python 编写 CSV 文件.
Here are some minimal complete examples how to read CSV files and how to write CSV files with 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)
之后,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']]
请注意,CSV 仅读取字符串.您需要手动转换为列类型.
Please note that CSV reads only strings. You need to convert to the column types manually.
之前有一个 Python 2+3 版本(链接),但是放弃对 Python 2 的支持.删除 Python 2 的东西大大简化了这个答案.
A Python 2+3 version was here before (link), but Python 2 support is dropped. Removing the Python 2 stuff massively simplified this answer.
查看我的实用程序包 mpu
以获得超级简单和容易记住的一个:
Have a look at my utility package mpu
for a super simple and easy to remember one:
import mpu.io
data = mpu.io.read('example.csv', delimiter=',', quotechar='"', skiprows=None)
mpu.io.write('example.csv', data)
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()
参见 read_csv
文档 了解更多信息.请注意,pandas 会自动推断是否有标题行,但您也可以手动设置.
See read_csv
docs for more information. Please note that pandas automatically infers if there is a header line, but you can set it manually, too.
如果您还没有听说过 Seaborn,我建议您看看它.
If you haven't heard of Seaborn, I recommend having a look at it.
许多其他库都支持读取 CSV 文件,例如:
Reading CSV files is supported by a bunch of other libraries, for example:
dask.dataframe.read_csv代码>
spark.read.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
.csv
在将 CSV 文件读取到元组/字典列表或 Pandas 数据框后,它只是在处理此类数据.没有特定的 CSV.
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.
对于您的应用程序,以下内容可能很重要:
For your application, the following might be important:
另请参阅:数据序列化格式的比较
如果您正在寻找一种制作配置文件的方法,您可能想阅读我的短文 Python 中的配置文件
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 读写 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!