How to Upload Files via FTP with Python


In this article, we show how to upload files via FTP using the ftplib module in Python.

FTP, which stands for File Transfer Protocol, is the standard network protocol used for the transmission of comjputer files between a client and a server on a computer network.

The ftplib module allows us to communicate with the FTP server in Python.

The ftplib module is a built-in standard module in Python. Therefore, it does not need to be installed. It just simply needs to imported at the top of the code.

Once imported we just need to specify the file you want to upload and the ftp address, as well as log into the ftp server account so that we are authenticated.

This is shown in the following code below.

So the first thing we have to do is import the ftplib module. This allows us to communicate with FTP servers so that we can upload files to a website via the FTP server. This is done through the line, import ftplib

We then create a variable, ftp, that references the server name of the FTP server you are trying to upload your file to.

We then have to log into the FTP server. This is one of the FTP users of the site.

You then must specify the directory on your site where you want to upload the file to. By default, the directory is the home or root directory of your website ('/'). But you can change this to whatever directory you want. In the code above, I change the directory to upload to to the Articles directory. This is done through the line, ftp.cwd('Articles')

After this, we must specify the complete path to the file on our local computer that we want to upload. I put the file on the Desktop of the user David, so I specify this file.

The last thing is to actually upload the file, which is done with the ftp.storlines() function. Inside of this function, we specify the keyword 'STOR ' followed by the filename of the file with the complete path specified to the file. This makes the upload possible.

If you didn't get an error message, then this upload most likely worked. Now if you go to the the new page on your computer, you should see the file uploaded.

Of course, in order to do FTP uploads with Python, you need an active internet connection, so that Python can connect with the FTP server.

And this how you can do file uploads via FPT using the ftplib module in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...