Python

How to Use FTP in Python?

Have you ever used any version control system or cloud network system in which you and your colleagues can update the data and fetch the files? If not, this article would be very beneficial for you. You may create Python programs that carry out several autonomous FTP tasks using the ftplib package in Python. To download files and manage them offline, users can instantly connect to something like an FTP server. Within this article, we will be discussing Python programs to use the FTP server and access its files at the local system.

Example 01:

Let’s get started with the first example of Python using FTP in its programs. For this, we have been using the Spyder 3 tool for the python program in Windows 10 system. This script must first establish a connection to an FTP server. We have created a new file named “test.py” in the Spyder 3 tool and saved it within the respective Spyder folder. We have been starting this code with the import of the “ftplib” library to use FTP in Python.

After this, we have been trying to connect to an FTP server using its official URL i.e., “ftp.nluug.nl”. This URL has been used within the “FTP” function via the use of the “ftplib” library of Python. The return result for this FTP function would be saved to the “FTP” object “f”. Using this FTP object “f”, we have been using the login() function of FTP to login from the FTP user using the anonymous username and it’s password or email to login. We have defined an empty list “v” that will be storing the list of documents and directories residing within the root folder of this FTP server. This “v” list has been using the “append()” function of Python to insert all the files and directories in the form of an array residing within the current working directory itself—within the “v” list via the “Dir” function.

After this, the FTP object has been used to close the connection to the server via the use of the quit() function of the FTP library. After this, we have been using the “v” list in the “for” loop to read all its data line by line and print it out all using the “print” function along with the line variable, taking each document or directory as an element of a list. Our code is now completed and we have saved it to execute.

import ftplib
f = ftplib.FTP("ftp.nluug.nl")
f.login("anonymous", "ftplib-example-1")
v = []
f.dir(v.append)
f.quit()
for line in v:
    print ("-", line)

On running this code in Spyder 3 using its run button, we have the list of all files that are available at the root directory of the FTP server on our Spyder Console. You can see that it displayed the privileges assigned to each directory along with their creation date and file name after that. There are some mirror files in the list as well as symlinks.

Example 02:

Within our first example, we have looked at how to list all the files and folders residing in the current root folder of your FTP server. Now, we will be listing the documents from the specific folder of your FTP server. For this, we have been utilizing quite the same code as we used in the first example. Thus, we have been starting this example with the import of the same ftplib library of Python to connect our program with the FTP server. We have been connecting our program with the same FTP server using the FTP function and anonymously login from it via the login() function of python.

After successful login using the object “f” of the FTP package of python, we have initialized an empty list “v” that will be used further. The “cwd()” function of the FTP module in python has been utilized to change the current working directory and move within a new folder i.e., “pub” of our FTP server. Now, we are at a different location of the FTP server and using the append function to insert all the files of the “pub” folder within the list “v” using the “dir” function.

The quit() function has been used to exit the FTP server. The “For” loop is here to print out each file in this “pub” folder as a separate line element.

import ftplib
f = ftplib.FTP("ftp.nluug.nl")
f.login("anonymous", "ftplib-example-1")
v = []
f.cwd('/pub/')
f.dir(v.append)
f.quit()
for line in v:
    print ("-", line)

After the execution of this updated code, we have all the files and folders from the “pub” folder displayed on the Console screen.

Example 03:

The above two examples were about listing the files from the FTP server on your console. Now, we will be taking a look at the use of the Python getFile() function of FTP to fetch the files from the FTP server into our local system.

For this, we have been defining the “getFile” function with the “F” object and filename. The try-catch exception handling has been used here to open the respective file from any folder of the server, make its copy using the “write” function, and save it to the local system using the “retrbinary” function. If that doesn’t happen, the except part will throw an exception.

After this, the connection to the server would be established and we move to the “pub” folder. The getFile() function has been called thrice to fetch different files each time. At last, we have closed the connection via the quit() function.

import ftplib
def getFile(f, filename):
    try:
        f.retrbinary("RETR " + filename ,open(filename, 'wb').write)
    except:
        print ("Error")
f = ftplib.FTP("ftp.nluug.nl")
f.login("anonymous", "ftplib-example-1")
f.cwd('/pub/')
getFile(f,'db')
getFile(f,'crypto')
getFile(f,'favicon.ico')
f.quit()

On running this program, we have got all three files in the local system as shown.

Conclusion

This article is containing a great explanation of the purpose of using the FTP server in python code: fetch the online files at your local system. We have discussed how the files from the FTP server can be listed in the console and how we can fetch them easily using the FTP functions.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content