【Python入门教程】第73篇 写入CSV文件

本篇我们介绍如何使用 Python 内置的 csv 模块将数据写入 CSV 文件。

写入 CSV 文件

在 Python 代码中写入 CSV 文件的步骤如下:

以下代码实现了上面的步骤:

import csv

# open the file in the write mode
f = open('path/to/csv_file', 'w')

# create the csv writer
writer = csv.writer(f)

# write a row to the csv file
writer.writerow(row)

# close the file
f.close()

使用 with 语句可以避免调用 close() 方法关闭文件,从而使得代码更加精简:

import csv

# open the file in the write mode
with open('path/to/csv_file', 'w') as f:
    # create the csv writer
    writer = csv.writer(f)

    # write a row to the csv file
    writer.writerow(row)

如果数据中包含非 ASCII 编码字符,需要在 open() 函数中指定字符编码。以下示例演示了如何将 UTF-8 字符写入 CSV 文件:

import csv

# open the file in the write mode
with open('path/to/csv_file', 'w', encoding='UTF8') as f:
    # create the csv writer
    writer = csv.writer(f)

    # write a row to the csv file
    writer.writerow(row)

示例

以下示例演示了如何将数据写入 CSV 文件:

import csv  

header = ['id', 'stu_id', 'course_name', 'course_score']
data = [1, 1, 'English', 100]

with open('score.csv', 'w', encoding='UTF8') as f:
    writer = csv.writer(f)
    # write the header
    writer.writerow(header)
    # write the data
    writer.writerow(data)

如果打开 score.csv 文件,我们会发现一个问题,就是两行数据之间存在一个额外的空白行:

【Python入门教程】第73篇 写入CSV文件
为了删除多余的空白行,我们可以为 open() 函数指定关键字参数 newline=’’:

import csv  

header = ['id', 'stu_id', 'course_name', 'course_score']
data = [1, 1, 'English', 100]

with open('score.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)
    # write the header
    writer.writerow(header)
    # write the data
    writer.writerow(data)

再次打开 score.csv 文件,显示的内容如下:

【Python入门教程】第73篇 写入CSV文件

写入多行数据

如果想要一次写入多行数据,我们可以使用 writerows() 方法。例如:

import csv  

header = ['id', 'stu_id', 'course_name', 'course_score']
data = [
    [1, 1, 'English', 100],
    [2, 1, 'Math', 95],
    [3, 2, 'English', 96]
]

with open('score.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)
    # write the header
    writer.writerow(header)
    # write the data
    writer.writerows(data)

新文件的内容如下:

【Python入门教程】第73篇 写入CSV文件

DictWriter 类

如果写入的数据行由字典组成,我们可以使用 csv 模块 的DictWriter 类将数据写入文件。例如:

import csv

# csv header
fieldnames = ['id', 'stu_id', 'course_name', 'course_score']

# csv data
rows = [
    {'id': 1,
    'stu_id': 1,
    'course_name': 'English',
    'course_score': 100},
    {'id': 2,
    'stu_id': 1,
    'course_name': 'Math',
    'course_score': 95},
    {'id': 3,
    'stu_id': 2,
    'course_name': 'English',
    'course_score': 96}
]

with open('score.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

以上代码的执行过程如下:

总结

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年3月12日 下午8:21
下一篇 2023年3月12日 下午8:25

相关推荐