Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

python - Value Error: I/O operation on closed file

 import requests
    import csv
    
    url = "https://paneledgesandbox.//API/v3/surveys/id/import-responses"
    
    with open('Cars.csv', 'r') as file:
        payload = csv.reader(file)
        print(payload)
    headers = {
      'X-API-TOKEN': 'zzzz',
      'Content-Type': 'text/csv',
      'Cookie': 'CPSessID=bb5b5cf55ceff2c2b8237810db3ca3a7; XSRF-TOKEN=XSRF_0wG1WMbV3G0ktBb'
    }

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)`

I am getting an error while trying to read a csv file in a post call using python.

I am not sure where exactly the issue is considering that using the with command, the file automatically closes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In

payload = csv.reader(file)

you are not actually reading your csv, but rather returning a generator which is exhausted after the file is closed when you go out of with's scope.

You need to read the data instead

payload = "
".join([", ".join(line) for line in csv.reader(file)])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...