How to List all Files and Directories in FTP Server using Python

Published on Aug. 22, 2023, 12:16 p.m.

To list all files and directories in an FTP server using Python, you can use the built-in ftplib module. Here is an example code that connects to an FTP server and lists all files and directories:

import ftplib

ftp = ftplib.FTP('ftp.example.com') # Replace 'example.com' with your server address
ftp.login(user='username', passwd='password') # Replace 'username' and 'password' with your credentials

files = []
ftp.cwd('/')
ftp.retrlines('LIST', lambda line: files.append(line.split()[-1]))

print(files)

In this code, we first connect to the FTP server using the ftp function and log in using the login credentials (replace them with your own). We then define an empty list called files and use the cwd() function to set the current directory to the root directory (you can change this to any desired directory). Next, we use the retrlines() function to retrieve a directory listing in LIST format, and the lambda function appends the filename (which is the last element in the line) to the files list. Finally, we print the files list to display all the file and directory names in the root directory.

Note that this code only lists files and directories in the current directory. If you want to list all files and directories recursively in the FTP server, you can make a function that uses the nlst() function to get a list of all files and directories and recursively loop through them to list all the files and directories.

Tags: