Valueerror error: I/O Operation on closed file. when generating csv with python

Asked

Viewed 3,453 times

0

My code is giving error of "ValueError: I/O operation on closed file."

and I can’t find it in any forum, does anyone know what it might be ? Thank you.

import json
import requests
import csv

url = 'https://api.suthubservice.com/v0/sales' 
headers = {'Content-Type' : 'application/json', 
 'api_key' : 'eb9484921d678843bbfdd6bf460a1df7' 
} 
response = requests.get(url, headers=headers) 
res = json.loads(response.text)

output = []

for contract in res['response']: # tomei a liberdade de mudar o nome da variável
     if len(contract['policies']) > 0:
         for profile in contract['policies'][0]['covered_goods']:
             output.append(profile['Nome'])

totais = {x:output.count(x) for x in output}

with open('C:\Desafio\cadastro.csv', 'r+', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=';')
    spamwriter.writerow(['nome_pet'] + ['contador'])


for nome,qtde in totais.items():
    spamwriter.writerow([nome]+[qtde])


for nome,qtde in totais.items():
    print(nome,qtde)
  • You left the comment I made in the past post in your code. Take another look at that post because I made a modification to get all the names in case the contract has more than one element policies.

1 answer

3


This mistake happens because at the end of with: open(...) as csvfile: the open file is closed. Then soon after you enter a for who tries to write to this file that has already been closed.

Put this on for within the with. Thus:

with open('C:\Desafio\cadastro.csv', 'r+', newline='') as csvfile: 
    spamwriter = csv.writer(csvfile, delimiter=';') 
    spamwriter.writerow(['nome_pet'] + ['contador']) 
    for nome,qtde in totais.items(): 
        spamwriter.writerow([nome]+[qtde])
  • Rafael, thank you very much! I’m starting now in language and there are some rules I didn’t know! Gratitude!

  • A tip: if an answer helped you and solved the exposed problem @Gleice tick the V on it so that other people who access here later know that the solution solved the problem. So when another person with a similar problem gets here, you’ll know that with the answer given the problem has been solved and that they can try the same method to solve theirs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.