[Tutor] File upload from python shell

Alan Gauld alan.gauld at btinternet.com
Sun Oct 14 10:04:46 CEST 2007

"Paulino" <paulino1 at sapo.pt> wrote

> How can I upload a file from python?

Just to be clear. You want to send a file from your computer
to another computer?

The simplest way to do that is using ftp. There is an ftp module.
However for that to work the receiving computer needs to be
running an ftp server.

> If it is a form to fill with values it's simple:
> urlopen("http://site.com/action?key1=value1;key2=value2")
> and I get the form filled.

That may not always work if the form relies on an HTTP/POST
request rather than a GET request. I'm not sure how you get
urllib to use POST. Hmm, checking the docs it says:

      urlopen( url[, data])

Open the URL url, which can be either a string or a Request object.
data may be a string specifying additional data to send to the server,
or None if no such data is needed. Currently HTTP requests are
the only ones that use data; the HTTP request will be a POST
instead of a GET when the data parameter is provided.
data should be a buffer in the standard 
format. The urllib.urlencode() function takes a mapping or sequence
of 2-tuples and returns a string in this format.

> What about uploading a file programmaticaly?

If you mean you want to submit a web form that requires a file
then the form will use a POST request, so you will need to create
a data string for the urlopen call using urlencode.

However, how a file would be encoded into a string I don't know!
I''ve never used POST requests in urllib. From a scan of the module
it looks like you may need to use a FileOpener object but its
not clear to me how that works.

Hopefully someone else has done this already and can help.

Alan G

More information about the Tutor mailing list