MEMOO
MEMOO
Published on 2025-04-21 / 2 Visits
0
0

Python写CSV文件

摘要:在本教程中,您将学习如何使用内置的 csv 模块将数据写入 CSV 文件。

写入 CSV 文件的步骤

要将数据写入 CSV 文件,请按照以下步骤操作:

  • 首先,使用 open() 函数以写入模式(w 模式)打开 CSV 文件。

  • 其次,通过调用 csv 模块的 writer() 函数创建一个 CSV 写入器对象。

  • 第三,通过调用 CSV 写入器对象的 writerow()writerows() 方法将数据写入 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 文件示例

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

import csv  

header = ['name', 'area', 'country_code2', 'country_code3']
data = ['Afghanistan', 652090, 'AF', 'AFG']

with open('countries.csv', 'w', encoding='UTF8') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write the data
    writer.writerow(data)

如果你打开 countries.csv 文件,你会看到一个问题,即文件内容中两行之间有一个额外的空行:

要去掉空行,你可以将关键字参数 newline='' 传递给 open() 函数,如下所示:

import csv

header = ['name', 'area', 'country_code2', 'country_code3']
data = ['Afghanistan', 652090, 'AF', 'AFG']


with open('countries.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write the data
    writer.writerow(data)

输出:

向 CSV 文件写入多行

要一次性向 CSV 文件写入多行,你可以使用 CSV 写入器对象的 writerows() 方法。

以下示例使用 writerows() 方法将多行写入 countries.csv 文件:

import csv

header = ['name', 'area', 'country_code2', 'country_code3']
data = [
    ['Albania', 28748, 'AL', 'ALB'],
    ['Algeria', 2381741, 'DZ', 'DZA'],
    ['American Samoa', 199, 'AS', 'ASM'],
    ['Andorra', 468, 'AD', 'AND'],
    ['Angola', 1246700, 'AO', 'AGO']
]

with open('countries.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write multiple rows
    writer.writerows(data)

使用 DictWriter 类写入 CSV 文件

如果 CSV 文件的每一行都是一个字典,你可以使用 csv 模块的 DictWriter 类将字典写入 CSV 文件。

以下示例说明了如何使用 DictWriter 类将数据写入 CSV 文件:

import csv

# csv header
fieldnames = ['name', 'area', 'country_code2', 'country_code3']

# csv data
rows = [
    {'name': 'Albania',
    'area': 28748,
    'country_code2': 'AL',
    'country_code3': 'ALB'},
    {'name': 'Algeria',
    'area': 2381741,
    'country_code2': 'DZ',
    'country_code3': 'DZA'},
    {'name': 'American Samoa',
    'area': 199,
    'country_code2': 'AS',
    'country_code3': 'ASM'}
]

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

其工作原理如下:

  • 首先,定义用于存储 CSV 文件的字段名称和数据行的变量。

  • 接下来,通过调用 open() 函数打开 CSV 文件以进行写入。

  • 然后,通过将文件对象(f)和 fieldnames 参数传递给 DictWriter 类,创建该类的一个新实例。

  • 之后,通过调用 writeheader() 方法为 CSV 文件写入表头。

  • 最后,使用 writerows() 方法将数据行写入 CSV 文件。

总结

  • 使用 CSV Writer 或 DictWriter 类将数据写入 CSV 文件。


Comment