如何在Python中向CSV文件添加新行?

2,563 阅读2分钟

Python向CSV添加行

要在现有的CSV中追加一行(=dictionary),使用open('my_file.csv', 'a', newline='') ,在追加模式打开文件对象。然后创建一个csv.DictWriter() ,用DictWriter.writerow(my_dict) 来追加一个dict行。

给定以下文件'my_file.csv'

你可以通过这个代码片断向CSV文件追加一行(dict)。

import csv

# Create the dictionary (=row)
row = {'A':'Y1', 'B':'Y2', 'C':'Y3'}

# Open the CSV file in "append" mode
with open('my_file.csv', 'a', newline='') as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter(f, fieldnames=row.keys())

    # Append single row to CSV
    writer.writerow(row)

在与你的原始'my_file.csv' 相同的文件夹中运行该代码后,你会看到以下结果。

向CSV文件追加多行

给出以下CSV文件。

要将多行(即dicts)添加到一个现有的旧CSV文件中,通过在最初创建的DictWriter 对象上调用csv.DictWriter.writerow(row) ,遍历这些行并写入每个row

下面是一个例子(主要的变化突出显示)。

import csv

# Create the dictionary (=row)
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open('my_file.csv', 'a', newline='') as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow(row)

结果CSV文件的第一行中加入了所有的三行。

Python向CSV添加行 Pandas

要使用Pandas在现有的CSV中添加一行,你可以在pandas DataFrame中设置写入mode ,参数为append'a' [to_csv()](https://blog.finxter.com/pandas-dataframe-to_csv-method/)方法中,像这样设置。df.to_csv('my_csv.csv', mode='a', header=False).

df.to_csv('my_csv.csv', mode='a', header=False)

对于一个完整的例子,请看这个代码片段。

import pandas as pd

# Create the initial CSV data
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Create a DataFrame and write to CSV
df = pd.DataFrame(rows)
df.to_csv('my_file.csv', header=False, index=False)

# Create another row and append row (as df) to existing CSV
row = [{'A':'X1', 'B':'X2', 'C':'X3'}]
df = pd.DataFrame(row)
df.to_csv('my_file.csv', mode='a', header=False, index=False)

输出文件看起来是这样的(新行突出显示)。

另外,你也可以在追加模式下使用普通的 [open()](https://blog.finxter.com/python-open-function/)函数打开带有append'a' 参数的文件,并将其传入pandas DataFrame [to_csv()](https://blog.finxter.com/pandas-to_csv/)方法中。

这里有一个复制&粘贴的例子片段。

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)