2

Hi I'm having trouble posting a text file using the Python Requests Library ( http://docs.python-requests.org/en/latest/index.html ), can you let me know what I'm doing wrong?

I tried searching for related questions and found this Send file using POST from a Python script but it doesn't answer my question.

Here's my code:

import codecs
import requests

# Create a text file
savedTextFile = codecs.open('mytextfile.txt', 'w', 'UTF-8')

# Add some text to it
savedTextFile.write("line one text for example\n and line two text for example")

# Post the file THIS IS WHERE I GET REALLY TRIPPED UP
myPostRequest = requests.post("https://someURL.com", files=savedTextFile)

I've tried a few variations on the above and I'm not getting anywhere (new error every time). How do I post this txt file that I just created? The API I'm trying to post to requires a text file to be posted to it.

Any help is appreciated!

Community
  • 1
  • 1

1 Answers1

5

The files parameter expects a dict of a filename matching to a file-handler. This is described in the source code (currently line 69):

Github Source (requests/models.py)

#: Dictionary of files to multipart upload (``{filename: content}``).
self.files = files

Sometimes the best documentation is the code.

Your last line should look like the following:

myPostRequest = requests.post("https://someURL.com", files={'mytextfile.txt': savedTextFile})
sudorandom
  • 407
  • 3
  • 13
  • I was going to add more to my answer because I also noticed that you only have the file open for writing. For requests to be able to actually read the file, you'll need to open the file for reading and writing. Additionally, you'll also need to reset the 'seek' to 0 after your done writing text. If the goal of this isn't to end up with a local file but just to post text as a file and the actual file is just a means to an end, I recommend using the StringIO module in the python standard library to write your text. It will act like a file but be completely in memory. – sudorandom Nov 12 '11 at 20:39