如何阅读以下 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
如何将以下 data
写入 CSV 文件?
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),
]
最佳答案
这里有一些最小的完整示例,如何读取 CSV 文件以及如何使用 Python 编写 CSV 文件。
Python 3:读取 CSV 文件
纯 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 仅读取字符串。您需要手动转换为列类型。
之前有 Python 2+3 版本(link),但是 Python 2 support is dropped .删除 Python 2 的东西大大简化了这个答案。
相关
- How do I write data into csv format as string (not file)?
- How can I use io.StringIO() with the csv module? :如果您想使用 Flask 即时提供 CSV,而不将 CSV 实际存储在服务器上,这很有趣。
微处理器
看看我的实用程序包mpu
对于一个 super 简单易记的:
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()
见 read_csv
docs了解更多信息。请注意,pandas 会自动推断是否有标题行,但您也可以手动设置。
如果您还没有听说过 Seaborn ,我建议你看看它。
其他
许多其他库都支持读取 CSV 文件,例如:
创建的 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。
替代方案
- JSON:非常适合编写人类可读的数据;非常常用(read & write)
- CSV: super 简单的格式(read & write)
- YAML:很好读,类似于 JSON (read & write)
- pickle:一种 Python 序列化格式 (read & write)
- MessagePack (Python package):更紧凑的表示 (read & write)
- HDF5 ( Python package ): 适用于矩阵 (read & write )
- XML: 也存在 *sigh* (read & write)
对于您的应用程序,以下内容可能很重要:
- 其他编程语言的支持
- 读/写性能
- 紧凑性(文件大小)
另请参阅:Comparison of data serialization formats
如果您正在寻找一种制作配置文件的方法,您可能需要阅读我的短文 Configuration files in Python
关于python - 如何使用 Python 读写 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41585078/