深度阅读

How to write to a CSV file in Python?

作者
作者
2023年08月22日
更新时间
9.77 分钟
阅读时间
0
阅读量

To write to a CSV file in Python, you can use the csv library or the pandas library. Here are two examples using both methods:

  1. Using the csv library:

import csv

with open(‘file.csv’, ‘w’, newline=’‘) as file:
writer = csv.writer(file)
writer.writerow([‘Column 1’, ‘Column 2’, ‘Column 3’]) # optional header row
writer.writerow([‘Value 1’, ‘Value 2’, ‘Value 3’])
writer.writerow([‘Value 4’, ‘Value 5’, ‘Value 6’])


2. Using the `pandas` library:

import pandas as pd

df = pd.DataFrame({‘Column 1’: [‘Value 1’, ‘Value 4’], ‘Column 2’: [‘Value 2’, ‘Value 5’], ‘Column 3’: [‘Value 3’, ‘Value 6’]})
df.to_csv(‘file.csv’, index=False)



Both methods involve opening the CSV file in a specified mode and writing data to it. The `csv` library provides fine-grained control over writing CSV files, while the `pandas` library provides a high-level interface to write out a `DataFrame` object to a CSV file with various formatting options.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。