Search code examples
pythonpython-requestsglob

How to make a dictionary in Python with files as keys?


I am trying to POST all files in a folder on my local drive to a certain web URL by using Requests and Glob. Every time I POST a new file to the URL, I want to add to a dictionary a new "key-value" item that is "name of the file (key), output from server after POSTing the file (value)":

import requests, glob, unicodedata

outputs = {}

text_files = glob.iglob("/Users/ME/Documents/folder/folder/*.csv")

url = 'http://myWebsite.com/extension/extension/extension'

for data in text_files:
    file2 = {'file': open(data)}
    r = requests.post(url, files=file2)
    outputs[file2] = r.text

This gives me the error:

Traceback (most recent call last):
  File "/Users/ME/Documents/folder/folder/myProgram.py", line 15, in <module>

    outputs[file2] = r.text
TypeError: unhashable type: 'dict'

This is because (I think) "file2" if of type 'dict'. Is there anyway to cast/alter 'file2' after I POST it to just be a string of the file name?


Solution

  • You are trying to use the file object, no the file name. Use data as the key:

    for data in text_files:
        file2 = {'file': open(data)}
        r = requests.post(url, files=file2)
        outputs[data] = r.text
    

    better yet, use a more meaningful name, and use with to have the open file object closed again for you:

    for filename in text_files:
        with open(filename) as fileobj:
            files = {'file': fileobj}
            r = requests.post(url, files=files)
        outputs[filename] = r.text