相关文章推荐
乖乖的荒野  ·  Spark ...·  8 月前    · 
风流倜傥的麦片  ·  Dependency ...·  1 年前    · 
·  阅读

CSV文件是存储结构化、表格式数据的最有效工具之一。有时,我们可能需要将数据从 python 字典 中追加到 CSV 文件中。在这篇文章中,我们将讨论如何用python将字典中的值追加到CSV文件中。

使用csv.writer()将字典追加到CSV文件中

你可以使用 CSV.writer() 方法和 CSV.writerow() 方法将一个字典追加到 CSV 文件。为此,我们将首先使用 open() 函数以追加模式打开 CSV 文件。 open() 函数将文件名作为它的第一个输入参数,将字面意思 " a " 作为它的第二个输入参数,以表示该文件是以追加模式打开的。

打开文件后,我们将使用 CSV.writer() 函数创建一个CSV写入器对象。 CSV.writer() 函数将包含CSV文件的文件对象作为其输入参数,并返回一个写作者对象。

创建完写作者对象后,我们将使用 w riterow()方法将字典追加到CSV文件中。 writerow() 方法,当对写作者对象调用时,将字典中的值作为其输入参数,并将其追加到 CSV 文件中。

在执行 writerow() 方法后,你必须用 close() 方法关闭 CSV 文件。否则,变化将不会被保存在 CSV 文件中。下面给出了这种将字典追加到 CSV 文件的方法的源代码。

import csv
myFile = open('Demo.csv', 'r+')
print("The content of the csv file before appending is:")
print(myFile.read())
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
writer = csv.writer(myFile)
writer.writerow(myDict.values())
myFile.close()
myFile = open('Demo.csv', 'r')
print("The content of the csv file after appending is:")
print(myFile.read())
The content of the csv file before appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the csv file after appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
4,Joel,Golang

使用csv.DictWriter()将字典追加到CSV文件中

我们可以不使用csv.writer() 方法,而使用csv.DictWriter() 函数和csv.writerow() 方法来追加一个 python 字典到 csv 文件。这个方法与使用csv.writer() 方法的方法几乎相似,但有以下区别。

  • 我们将使用csv.DictWriter() 方法,而不是 csv.writer() 方法。DictWriter() 方法将包含 csv 文件的文件对象作为其输入参数,并返回一个 DictWriter 对象。
  • writerow() 方法在 DictWriter 对象上执行时,它接受一个字典作为输入参数,而不是字典中的值。
  • 使用csv.DictWriter() 向 csv 文件追加一个字典的 python 代码如下。

    import csv
    myFile = open('Demo.csv', 'r+')
    print("The content of the csv file before appending is:")
    print(myFile.read())
    myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
    print("The dictionary is:")
    print(myDict)
    writer = csv.DictWriter(myFile, fieldnames=list(myDict.keys()))
    writer.writerow(myDict)
    myFile.close()
    myFile = open('Demo.csv', 'r')
    print("The content of the csv file after appending is:")
    print(myFile.read())
    
    The content of the csv file before appending is:
    Roll,Name,Language
    1,Aditya,Python
    2,Sam, Java
    3, Chris, C++
    The dictionary is:
    {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
    The content of the csv file after appending is:
    Roll,Name,Language
    1,Aditya,Python
    2,Sam, Java
    3, Chris, C++
    4,Joel,Golang
    

    在这篇文章中,我们讨论了两种在 python 中向 csv 文件追加字典的方法。在这些方法中,无论字典与csv文件中的列相比是否有相同数量的项目,或者与csv文件中的列名相比是否有相同的键,字典都将被追加。因此,建议确保字典中的键数与 csv 文件中的列数相同。你还应该确保 csv 文件中的列的顺序应该与字典中的键的顺序相同。否则,追加到 csv 文件的数据将变得不一致,并导致错误。

    我希望你喜欢阅读这篇文章。

    分类:
    人工智能
    标签: