写入和读取 csv 文件 - I/O 操作错误

Writing and reading to a csv file - I/O operation error

我需要创建一个文件并在 for 循环之前写入其 header 内容。如果我在循环内执行此操作,则 header 内容会在循环的每次迭代中重复。当我执行下面的代码时,出现错误 "I/O operation on a closed file".

想知道是否有解决此问题的方法?任何建议,将不胜感激。 TIA!!

    csv_filename = "testfile4.csv"
    with open(csv_filename, "wt") as csvfile:
        writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

        # CSV Header
        header = ["Post ID", "Permalink", "Create Time"]
        writer.writerow(header)

    for group in getGroups():
        feed = getValues(group["id"], group["name"])
        with open(csv_filename, "a") as csvfile:
            for item in feed:
                row = [item["id"], item["permalink_url"], item["created_time"]]
                writer.writerow(row)

您可以在单个 with 语句中处理所有必要的操作

csv_filename = "testfile4.csv"
with open(csv_filename, "wt") as csvfile:
    writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    header = ["Post ID", "Permalink", "Create Time"]
    writer.writerow(header)
    for group in getGroups():
        feed = getValues(group["id"], group["name"])
        for item in feed:
            row = [item["id"], item["permalink_url"], item["created_time"]]
            writer.writerow(row)