要在 Python 中写入 CSV,请使用 Python 的 csv 模块。

例如,让我们将一个字符串列表写入一个新的 CSV 文件:

import csv
data = ["This", "is", "a", "Test"]
with open('example.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(data)

 因此,您会在当前文件夹中看到一个名为 example.csv 的文件。

用 Python 编写 CSV 的 4 个步骤
要在 Python 中写入 CSV 文件:

1. 以写入模式打开 CSV 文件。 这是使用 open() 函数发生的。 给它文件的路径作为第一个参数。 将模式指定为第二个参数(“r”表示读取,“w”表示写入)。
2. 创建 CSV 编写器对象。 为此,创建一个 csv 模块的 writer() 对象,并将打开的文件作为其参数传递。
3. 将数据写入 CSV 文件。 使用 writer 对象的 writerow() 函数将数据写入 CSV 文件。
4. 关闭 CSV 文件,使用文件的 close() 方法。



这是一个说明此过程的示例:

import csv
# 1.
file = open('test.csv', 'w')
# 2.
writer = csv.writer(file)
# 3.
data = ["This", "is", "a", "Test"]
writer.writerow(data)
# 4.
file.close()

这段代码在当前文件夹中创建了一个名为 test.csv 的文件。

如果指定的文件不存在,open() 函数将打开一个新文件。 如果是,则打开现有文件。

速写

要缩短写入 CSV 的时间,请使用 with 语句打开文件。 这样你就不用担心自己关闭文件了。 with 会自动处理该部分。

例如:

import csv
# 1. step
with open('test.csv', 'w') as file:
    # 2. step
    writer = csv.writer(file)
    # 3. step
    data = ["This", "is", "a", "Test"]
    writer.writerow(data)

这将在当前文件夹中创建一个名为 test.csv 的新 CSV 文件,并将字符串列表写入其中。

如何在 Python 中将非 ASCII 字符写入 CSV

默认情况下,您不能将非 ASCII 字符写入 CSV 文件。

要支持将非 ASCII 值写入 CSV 文件,请在 open() 调用中将字符编码指定为第三个参数。

with open('PATH_TO_FILE.csv', 'w', encoding="UTF8")

其余过程遵循您之前学到的步骤。

如何为 CSV 文件创建标题

到目前为止,您已经创建了缺少结构的 CSV 文件。

在 Python 中,可以使用用于将任何数据写入 CSV 

writerow() 函数为任何 CSV 文件编写标头。

 例子:  让我们创建一个包含学生数据的示例 CSV 文件。

为了很好地构建数据,为学生创建一个标题并将其插入 CSV 文件的开头。 在此之后,您可以按照之前的相同步骤将数据写入 CSV 文件。

这是代码:

import csv
# Define the structure of the data
student_header = ['name', 'age', 'major', 'minor']
# Define the actual data
student_data = ['Jack', 23, 'Physics', 'Chemistry']
# 1. Open a new CSV file
with open('students.csv', 'w') as file:
    # 2. Create a CSV writer
    writer = csv.writer(file)
    # 3. Write data to the file
    writer.writerow(student_header)
    writer.writerow(student_data)

这会将 students.csv 文件创建到您当前正在使用的文件夹中。新文件如下所示:

 

 

如何在 Python 中将多行写入 CSV 文件

在 Python 中,您可以使用 CSV 编写器的 writerows() 函数同时将多行写入 CSV 文件。

例子。 假设您要将多行数据写入 CSV 文件。 例如,您可能有一个学生列表,而不是只有其中一个。

要将多行数据写入 CSV,请使用 writerows() 方法。

这是一个例子:

import csv
student_header = ['name', 'age', 'major', 'minor']
student_data = [
    ['Jack', 23, 'Physics', 'Chemistry'],
    ['Sophie', 22, 'Physics', 'Computer Science'],
    ['John', 24, 'Mathematics', 'Physics'],
    ['Jane', 30, 'Chemistry', 'Physics']
]
with open('students.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(student_header)
    # Use writerows() not writerow()
    writer.writerows(student_data)

 这会生成一个新的 CSV 文件,如下所示:

 

如何在 Python 中将字典写入 CSV 文件

要在 Python 中将字典写入 CSV 文件,请按照以下三个步骤使用 DictWriter 对象:

1. 使用 csv 模块的 DictWriter 对象并在其中指定字段名称。
2. 使用 writeheader() 方法将标头创建到 CSV 文件中。
3. 使用 writerows() 方法将字典数据写入文件。
例子:让我们将学生数据字典写入 CSV 文件。

import csv
student_header = ['name', 'age', 'major', 'minor']
student_data = [
    {'name': 'Jack', 'age': 23, 'major': 'Physics', 'minor': 'Chemistry'},
    {'name': 'Sophie', 'age': 22, 'major': 'Physics', 'minor': 'Computer Science'},
    {'name': 'John', 'age': 24, 'major': 'Mathematics', 'minor': 'Physics'},
    {'name': 'Jane', 'age': 30, 'major': 'Chemistry', 'minor': 'Physics'}
]
with open('students.csv', 'w') as file:
    # Create a CSV dictionary writer and add the student header as field names
    writer = csv.DictWriter(file, fieldnames=student_header)
    # Use writerows() not writerow()
    writer.writeheader()
    writer.writerows(student_data)

现在结果与前面示例中的 students.csv 文件相同:

 

结论

CSV 或逗号分隔值是一种常用的文件格式。 它由通常用逗号分隔的值组成。

要在 Python 中写入 CSV,您需要通过以下步骤使用 csv 模块:
1. 以写入模式打开 CSV 文件。
2. 创建 CSV 编写器对象。
3. 将数据写入 CSV 文件。
4. 关闭 CSV 文件。
这是一个实际的例子。

import csv
data = ["This", "is", "a", "Test"]
with open('example.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(data)

编码愉快!

物联沃分享整理
物联沃-IOTWORD物联网 » Python读写csv文件

发表评论