使用 ftplib
模块在 Python 中下载整个文件夹稍微有些复杂,因为 ftplib
本身并不直接支持下载整个目录。你需要递归地列出目录中的所有文件和子目录,然后逐个下载。
以下是一个简单的示例,说明如何使用 ftplib
从 FTP 服务器下载整个文件夹:
from ftplib import FTP_TLS, error_perm
import os
def download_directory(ftp, local_path, remote_path, username, password):
try:
ftp.login(user=username, passwd=password)
ftp.cwd(remote_path) # Change working directory to the remote path
# List all the files and directories in the remote path
files = ftp.nlst()
# Create the local directory if it doesn't exist
os.makedirs(local_path, exist_ok=True)
for file in files:
remote_file_path = os.path.join(remote_path, file)
local_file_path = os.path.join(local_path, file)
# Check if it's a directory and recursively call the function
if ftp.dir(remote_file_path, file):
download_directory(ftp, local_file_path, remote_file_path, username, password)
else:
with open(local_file_path, 'wb') as f:
ftp.retrbinary('RETR ' + remote_file_path, f.write)
except error_perm as e:
if str(e) == "550 No files found":
print(f"No files found in {remote_path}")
else:
raise
finally:
ftp.quit()
# Usage
ftp = FTP_TLS()
ftp.connect('ftp.example.com') # Replace with your FTP server
download_directory(ftp, '/path/to/local/directory', '/path/on/ftp/server', 'username', 'password')
注意:
- 替换
ftp.example.com
、/path/to/local/directory
、/path/on/ftp/server
、username
和password
为你的实际 FTP 服务器信息和本地路径。 - 此代码仅适用于非加密的 FTP 连接。如果你需要使用 FTPS(FTP Secure),请确保你的 FTP 服务器支持并正确配置了 FTPS。
- 此代码可能会因为 FTP 服务器的不同实现或配置而有所不同,你可能需要根据实际情况进行调整。
另外,考虑到 ftplib
的功能和灵活性,有些情况下可能更适合使用第三方库,如 pyftplib
,它提供了更多的功能和更好的错误处理。