深度阅读

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

作者
作者
2023年08月22日
更新时间
14.61 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。