How To Share Files With Python

A lot of times I find myself wanting to send a friend a file or receive a file from them. There are tons of products designed around syncing files and have some support for sharing them like, Google Drive, Drop Box and iCloud, but the situation I’m describing is more for “one off” file shares.

As most software developers know, there are a series of protocols designed for sharing files, such as SMB and S/FTP and tools such as scp and rsync. The situation I’m describing is when you want to share a file with a non technical individual. For this situation the protocols and tools described above will prove to be over their heads without some explanation or careful guidance.

Python to the rescue! Python ships with a built in HTTP Server! A HTTP server’s job is to serve up files by responding to HTTP requests.

Note: This technique would require both parties to be on the same network. If one wants to share files in between networks, one would have to open a port on their router. While functional, this exposes yourself to the internet, which is not incredibly safe. If you do do this, please act as the files your sharing will be accessible to the world.

We can leverage this built in HTTP server by running it in the directory that contains the file(s) we wish to share.

`$ cd /some/path/with/our/files`

Then we can start our HTTP Web Server.

`$ python3 -m http.server`

By default, the HTTP Web Server will listen on port 8000 and can be accessed by navigating to your device’s IP address and port 8000. EX: This will list the contents of that directory and let you download any of them.

One can modify the port by by passing in an int at the end.

$ python3 -m http.server 1234

It’s useful to use the bind flag to allow a machine from any ip address to download files.

$ python3 -m http.server 1234 --bind

One more neat approach is someone can download these files using wget or curl, like one would with any other HTTP server.

$ wget [ip address]:[port]/file-name

$ curl [ip address]:[port]/file-name -o file-name

Read more in the official docs.

What’s also neat about this approach is one can use it to host a web server on one’s Android phone. I’ve done this before using the application termux.