How to use FTP in Python

In this article, you will learn how to use FTP in your Python programs. You can do this with the help of ftplib module. FTP is File Transfer Protocol which is basically used for transferring files to and from a remote server. ftplib module allows you to use FTP tasks into your Python program and do many FTP related jobs such as retrieving files and processing them on your system.

Use FTP in Python

To start using this feature you need to import ftplib module into your program by

import ftplib

First, you have to connect the program to the FTP server to “open” the connection. For this, an object has to be created. When the connection is opened(made) then you can use the features of ftplib module. You can easily browse through the directory structure, download and uploading files, etc.

For this use the commands

from ftplib import FTP

ftp = FTP(‘domain.name’)

//To connect to a server anonymously. Kindly replace domain.name with your Domain Name. (Note -Place Domain Name inside the quotes)

To check if connected successfully.

print(ftp.getwelcome())

//This will show a message sent by the server in response to the connection request.

Now we have to log in to the server

ftp.login()

//To Login anonymously meaning when a username and password is not required.

If you a username or password

ftp.login(user=”username” passwd=”password”)

//To log in when you have a username and password. Kindly replace username with your User Name and password with your Password (Note- Within quotes “ ”)

After login command, this will show a message generally starting with a number like 230, 430 or 226

These are standard codes. Here for example 230 means  “User logged in, Logout if appropriate” 430 means “Username and Password Invalid”.

There are many methods in FTP class like delete(), quit(), connect(), cwd(), mkd().

Now let us write a simple program to retrieve files from the server

ftp=FTP(“domain name”)
ftp.login()
print(ftp.getWelcome())
ftp.retrlines('LIST')

Now this will show you the files present in the server. The output will be something like this.

https://drive.google.com/open?id=1WcGrfBe1yctlYGd_C6nrijw7WYeqCzn1

 

File Transfers in Python using FTP

To transfer files from the server you would have to know if it is a single block of binary code or a text file. So here FTP.retrlines() and FTP.retrbinary() method is used respectively.

In the above code retrlines(‘LIST’) is used to retrieve files or folders from the server in ASCII transfer mode. Proper command in retrlines() must be passed such as LIST, MLSD or NLST.

“LIST” is used to retrieving file names with their details.

NLST only retrieve file names.

from ftplib import FTP   
import os   

def writedata(info):   
     info.write(info)   
     info.write(os.linesep)   

ftp = FTP('Domain.name')   
ftp.login()   
ftp.cwd('path')   
info = open('file_name', 'wb')   
ftp.retrlines('RETR file_name', writedata)   
info.close()   

ftp.quit()  

Inline 1 and 2 we’re importing libraries ftplib as FTP and os module.

Inline 4 to 6 we declared a function to write text to a file line by line.

Now inline 8 and 9 we are connecting to the FTP server and logging in anonymously.

Inline 10 we are navigating to a specified ‘path’.

Inline 11 to 13 we are creating a file object to open the file in the FTP server as ‘wb’, ‘b’ for binary and “w’ as write. Pass file_name(replace with File Name) and write data into it locally on your machine. Then closing the file. And at last line 15 logging out of the server.

Binary File Transfer in Python using FTP

retrbinary() is used to retrieve the file in binary mode.

Proper RETR command and function should be passed in retrbinary()

Like ‘RETR file_name’ // Replace file_name with the name of the file you want to write to.

The function is for each block of data received.

from ftplib import FTP  
import os  
ftp = FTP('domain.name')  
ftp.login()  
ftp.cwd('path')  
info = open('file_name', 'wb')  
ftp.retrbinary('RETR file_name', info.write)  
info.close()  
ftp.quit() 

Try this, its similar to last code.

FTP.dir()

Shows the directory listing in your present working directory.

FTP.cwd(“pathHere”)

To change the directory you are working in you can use this.

//Replace pathHere with Path you want to get to.

FTP.mkd(path)

It creates a new directory taking a specific path.

FTP.pwd()

Shows the present working directory, pathname where you are at present.

FTP.delete(file_name)

Deletes a file having name (fle_name)  from the server.

FTP.quit()

It sends a request to close the connection with the server and log out.

FTP.close()

quit() command is like this command but close() renders the following FTP calls useless after it is executed.

No FTP commands should be executed after this.

Also read: Check if a string is a valid URL or not in Python

Leave a Reply

Your email address will not be published. Required fields are marked *