Apolymoxic Apolymoxic - 1 year ago 70
Python Question

Post CSV file contents as data in Python

Again, relatively new to python, so this may seem like a no-brainer to some people. My apologies in advance.

I would like to know how to open a .csv file and send the contents as data in a post session.

Something kind of like this:

userData = json.loads(loginResponse.text)
sessionToken = userData["sessionId"]
print ('Login successful! Attempting to upload file...')

# Now try to upload file
uploadURL = 'url'
headers = {
'token': sessionToken

with open('data.csv', newline='') as csvFile:
csvReader = csv.reader(csvFile)

uploadResponse = loginAS.post(uploadURL, headers=headers, data='CONTENTS OF CSV FILE')
print (uploadResponse.status_code)

I have tried to just open the csv file, but that didn't work. And I've tried


But I get a 'too many values to unpack' error. So, any ideas?

I'm not sure if it matters, but I am using Python 3.4

Answer Source

If you want to pass the file contents as simply a big blob of text, don't use the csv module at all. Just use the normal file read() method:

uploadResponse = loginAS.post(..., data=csvFile.read())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download