python - 如何使用 Python 读写 CSV 文件?

标签 python 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

如何将以下 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 的东西大大简化了这个答案。

相关

微处理器

看看我的实用程序包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。

替代方案

对于您的应用程序,以下内容可能很重要:

  • 其他编程语言的支持
  • 读/写性能
  • 紧凑性(文件大小)

另请参阅:Comparison of data serialization formats

如果您正在寻找一种制作配置文件的方法,您可能需要阅读我的短文 Configuration files in Python

关于python - 如何使用 Python 读写 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41585078/

相关文章:

python - Python/Pygame 中用于识别按键的正则表达式

r - 如何在 R 中保留/重新评估 data.frame 的因子水平?

javascript - 用于保存解析的 csv 公交路线数据的数据结构

c# - 如何将 EnumConverter 与 CsvHelper 一起使用

python - 如果条件不返回真

python - 如何向此代码添加打印语句而不会出现缩进错误

python - 通过正则表达式分割,不会在 Python 中产生空字符串

python - 使用 csv 阅读器后无法使用

mysql - 通过pymysql多进程更新MYSQL一张表

python - 删除所有满足正则表达式条件的行