Search code examples
pythonfilecsvwriter

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


I need to create a file and write its header contents before the for loop. If I do it inside the loop, header content repeats for every iteration of the loop. When I execute the below code, I get the error "I/O operation on a closed file".

Is wondering there a work around for this issue? Any suggestions would be appreciated. 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)

Solution

  • You could process all necessary operations in single with statement

    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)