Python @ DjangoSpin

Using the Standard Library Module ftplib

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

ftplib in Python

ftplib in Python

ftplib in Python: Python's standard library module ftplib enables users to carry out operations on a remote system using File Transfer Protocol. You can transfer files, fetch directory listing, create directories etc. on the connected system. Following are a few chosen operations, you can view the complete list of functionality that the ftplib offers by visiting its documentation.

Creating an FTP connection

>>> import ftplib
>>> ftpConnection = ftplib.FTP()
>>> ftpConnection.connect('ftp.yourDomainHere.com')		
>>> ftpConnection.login('yourUsername', 'yourPassword')		

# The connect() method returns a welcome message from FTP server with status code 220 if connection successful. If unsuccessful, it raises socket.gaierror saying '[Errno 11001] getaddrinfo failed'.
# The login() method returns a success message with status code 230 if credentials are correct. If unsuccessful, it raises ftplib.error_perm saying '530 Login incorrect' 

# Alternatively, you can provide this information to the constructor of the FTP class, in order to reduce method calls.
>>> ftpConnection3 = ftplib.FTP('ftp.yourDomainHere.com', 'yourUsername', 'yourPassword')

Getting present working directory

>>> ftpConnection.pwd()

Retrieving directory listing

>>> ftpConnection.dir()
# The dir() method gives long form of constituents of the current directory with information such as file permissions, created by, creation date & time etc.

# Alternatively, you can use th nlst() method.
>>> ftpConnection.nlst()
# The nlst() method returns a list of directories & files in the current directory. To view contents of a subdirectory, enter the name of subdirectory as an argument e.g. ftpConnection.nlst('subDirectoryOne').

# Alternatively, you can use the retrlines() method. The retrlines() method lists directories with either 'NLST' or 'LIST' as its argument. 
>>> ftpConnection.retrlines('LIST')											# output similar to dir()
>>> ftpConnection.retrlines('NLST')											# output similar to nlst()

Changing current working directory

>>> ftpConnection.cwd('subDirectoryOne')

# To move up a directory, enter two dots in the arguments.
>>> ftpConnection.cwd('..')

Deleting a file

>>> ftpConnection.delete('fileName')

Creating a directory

>>> ftpConnection.mkd('subDirectoryOneUnderSubDirectoryOne')

Removing a file/directory

ftpConnection.rmd('subDirectoryOneUnderSubDirectoryOne')

# The above works fine if the directory is empty. If it is not empty, you will receive an error saying the directory is not empty. In such a case, use the following code snippet to remove a non-empty directory.

Emptying a non-empty directory


# Navigate to the directory containing the non-empty directory, then call the following function.
def emptyNonEmptyDirectory():
	files = ftpConnection.nlst()
	
	for file in files:
		try:										# If file is not a directory
			ftpConnection.delete(file)
		except:										# If file is a directory 
			try:									# if directory is empty
				ftpConnection.rmd(file)
			except:									# if directory is not empty
				ftpConnection.cwd(file)
				emptyNonEmptyDirectory()
				ftpConnection.cwd('..')
				ftpConnection.rmd(file)
				
# Now that the directory is empty, call the rmd() method on it to delete it.

Renaming a directory

>>> ftpConnection.rename('subDirectoryOne', 'subDirectoryTwo')

Downloading a file

# Navigate to directory on remote system where you file is placed. Then, execute the following to download the file.
>>> ftpConnection.retrbinary('RETR fileNameOnRemoteSystem.txt', open(r'fullPathToNewFileOnLocalSystemIncludingNewFileName', 'wb'))

Uploading a file

# Navigate to directory where you want to place the file. Then execute the following.
>>> ftpConnection.storbinary('STOR fileNameOnRemoteSystem', open(r'fullPathToFileOnLocalSystemIncludingFileName', 'rb'))

Uploading a folder

# Contents of dirOne
|subDirOne
|--subDirOneFileOne.txt
|--subDirOneFileTwo.txt
|subDirTwo
|fileOne.txt
|fileTwo.txt


directoryToMove = r'pathToDirectoryOnLocalSystem'

def uploadDirectory(pathOfDirectoryToMove):
	import os
    files = os.listdir(pathOfDirectoryToMove)				# ['fileOne.txt', 'fileTwo.txt', 'subDirOne', 'subDirTwo']
    os.chdir(pathOfDirectoryToMove)											# changes current working directory to pathTo_dirOne
	
    for file in files:
		# if file is not a directory, then transfer it.
        if os.path.isfile(pathOfDirectoryToMove + r'\{}'.format(file)):		
            fileHandler = open(file, 'rb')
            ftpConnection.storbinary('STOR {}'.format(file), fileHandler)
            fileHandler.close()			
		# if file is a directory, make a directory by the same name on the remote system, access it, and call uploadDirectory() again to process its contents.
        elif os.path.isdir(pathOfDirectoryToMove + r'\{}'.format(file)):
            ftpConnection.mkd(file)
            ftpConnection.cwd(file)
            uploadDirectory(pathOfDirectoryToMove + r'\{}'.format(file))
			
    ftpConnection.cwd('..')
    os.chdir('..')											# go back to parent directory
	
uploadDirectory(directoryToMove) 

Executing FTP commands

# The sendcmd() method allows you to execute FTP commands and receive a response string from the server. A list of valid FTP commands can be viewed from https://en.wikipedia.org/wiki/List_of_FTP_commands or by executing ftpConnection.sendcmd('HELP'). A couple of usage examples:
>>> ftpConnection.sendcmd('PWD')
>>> ftpConnection.sendcmd('CDUP')
>>> ftpConnection.sendcmd('QUIT')

Closing an FTP connection

>>> ftpConnection.close()

Helpful Links

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply