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

时间:2017-08-17 17:54:06

标签: python file csv writer

我需要在for循环之前创建一个文件并写入其标题内容。如果我在循环内部执行此操作,则会在循环的每次迭代中重复标题内容。当我执行下面的代码时,我收到错误“关闭文件的I / O操作”。

想知道这个问题有解决办法吗?任何建议,将不胜感激。 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)

1 个答案:

答案 0 :(得分:0)

您可以在单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)