在Python 3中读取、更新和写入更新的CSV文件

在Python 3中读取、更新和写入更新的CSV文件,python,file,csv,output,Python,File,Csv,Output,我正在创建一个应用程序,基本上充当一个资产数据库,我正在尝试打开一个CSV文件,读取值并相应地更新它们。我看到很多关于如何读写CSV文件的教程,但我找不到一个详细介绍如何迭代CSV文件和更新单个值的教程。理想情况下,使用字典似乎比使用列表更容易,这样我就可以按关键字部件名进行搜索。它在大多数情况下都有效,但我在将更新的列表写入CSV文件时遇到了问题。我得到以下错误:第155行,以书面形式 将self.writer.writerowself.\u dict\u返回到\u listrowdict V

我正在创建一个应用程序,基本上充当一个资产数据库,我正在尝试打开一个CSV文件,读取值并相应地更新它们。我看到很多关于如何读写CSV文件的教程,但我找不到一个详细介绍如何迭代CSV文件和更新单个值的教程。理想情况下,使用字典似乎比使用列表更容易,这样我就可以按关键字部件名进行搜索。它在大多数情况下都有效,但我在将更新的列表写入CSV文件时遇到了问题。我得到以下错误:第155行,以书面形式 将self.writer.writerowself.\u dict\u返回到\u listrowdict ValueError:对关闭的文件执行I/O操作

def write(part_name, part_num="null"):

    with open("Database.csv", "r") as file_read:

        fieldnames=["Part_Name", "Part_Num"]
        csv_reader = csv.DictReader(file_read, fieldnames=fieldnames)

        temp_list = [] # Create temp copy of the csv file

        for line in csv_reader: # Reading the CSV file and storing it in temp_list
            temp_list.append(line)

        for line in temp_list: # Printing the original list to verify contents were read correctly
            print (line)

        for line in temp_list: # Reading each element in the list and updating the value if different from the value passed into the function
            if (line["Part_Name"] == part_name and line["Part_Num"] != part_num):
                line["Part_Num"] = part_num

        for line in temp_list: # Printing out the new vesion of the temp_list to verify updates took
            print (line)

        with open("Database.csv", "w") as file_write: 
            csv_writer = csv.DictWriter(file_write, fieldnames=fieldnames)

        for line in temp_list: # Attempting to write the updated temp_list to the csv file
            csv_writer.writerow(line)

在尝试再次打开该文件进行写入之前,需要确保该文件已在with语句之外关闭:

import csv

def update(part_name, part_num="null"):
    fieldnames = ["Part_Name", "Part_Num"]
    data = [] # Create temp copy of the csv file

    with open("Database.csv", "r", newline="") as file_read:
        csv_reader = csv.DictReader(file_read, fieldnames=fieldnames)
        header = next(csv_reader)

        for line in csv_reader: # Reading the CSV file and storing it in temp_list
            if line["Part_Name"] == part_name and line["Part_Num"] != part_num:
                line["Part_Num"] = part_num
            data.append(line)

    with open("Database.csv", "w", newline="") as file_write: 
        csv_writer = csv.DictWriter(file_write, fieldnames=fieldnames)
        csv_writer.writeheader()
        csv_writer.writerows(data)

使用CSV库时,应使用newline=参数打开文件。

第二个with语句位于第一个with语句的内部,这可能会导致问题,但尝试写入数据库的最终for循环位于打开文件进行写入的with块的外部,所以文件在那一点上是关闭的。当然它是那么简单。。。非常感谢你,我很抱歉浪费时间发布这篇文章。否决票绝对有理由。嗨,欢迎来到SO!我在复习第一篇文章。看起来这个问题已经解决了,但我想给你一些提示,让你问一个更好的问题。我保证,我们不会因为一个问题有一个明显的答案就投反对票!理想情况下,您的问题将提供一个最少的代码示例来演示您不理解的行为,但很明显,您的示例中有很多内容可以删除。明白。感谢您的反馈。这里的问题是您使用的是一个文本文件,而CSV就是用来做数据库工作的。我可以建议使用数据库吗?最简单的是sqlite3,它是Python标准库的一部分。