【问题标题】:Reading, Updating, and Writing updated CSV file in Python 3在 Python 3 中读取、更新和写入更新的 CSV 文件
【发布时间】:2018-01-06 02:47:52
【问题描述】:

我正在创建一个本质上充当资产数据库的应用程序,并且我正在尝试打开一个 CSV 文件,读取值并相应地更新它们。我看到许多关于如何读取和写入 CSV 文件的教程,但我找不到详细说明如何遍历 CSV 文件和更新单个值的教程。理想情况下,使用字典似乎比使用列表更容易,因此我可以按关键字(零件名称)进行搜索。它在大多数情况下都有效,但我在将更新的列表写入 CSV 文件时遇到问题。我收到以下错误:“第 155 行,在 writewrow 返回 self.writer.writerow(self._dict_to_list(rowdict)) 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 语句位于第一个 with statement 内,这可能会导致问题,但您尝试写出数据库的最后一个 for 循环也是 outside 在您打开文件进行写入的with 块中,因此文件在该点关闭。
  • 当然就是这么简单...非常感谢您,对于浪费时间发布此内容,我深表歉意。绝对有理由投反对票。
  • 您好,欢迎来到 SO!我正在审查第一个帖子。看起来问题已经解决了,但我想提供一些关于提出更好的 SO 问题的提示。 (我保证,我们不会仅仅因为一个问题有一个明显的答案而投反对票!)理想情况下,您的问题将提供一个代码的最小示例来展示您不理解的行为,但显然有很多可以从您的例子。
  • 明白。感谢您的反馈。
  • 这里的问题是您正在使用文本文件(即 CSV 文件)来完成数据库的工作。我可以建议使用数据库吗?最简单的是 sqlite3,它是 Python 标准库的一部分。

标签: python file csv output


【解决方案1】:

您需要确保文件已关闭(在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="" 参数打开文件。

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2021-07-29
    • 2017-06-18
    • 2021-03-29
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多