Python编程:Ftp
ftplib是Python标准库中用于FTP(文件传输协议)操作的模块,支持上传、下载文件以及基本的FTP服务器操作。
·
ftplib
是Python标准库中用于FTP(文件传输协议)操作的模块,支持上传、下载文件以及基本的FTP服务器操作。
基本使用方法
1. 连接FTP服务器
from ftplib import FTP # 创建FTP连接 ftp = FTP('ftp.example.com') # FTP服务器地址 ftp.login(user='username', passwd='password') # 登录 # 匿名登录(如果服务器允许) # ftp.login() # 不提供用户名和密码 print(f"欢迎消息: {ftp.getwelcome()}")
2. 基本目录操作
# 获取当前工作目录 current_dir = ftp.pwd() print(f"当前目录: {current_dir}") # 更改目录 ftp.cwd('/pub/downloads') # 切换到指定目录 # 列出目录内容 ftp.dir() # 详细列表(类似ls -l) # 或获取文件名列表 files = ftp.nlst() print("目录内容:", files)
3. 文件下载
# 下载文本文件 with open('local_file.txt', 'wb') as f: ftp.retrbinary('RETR remote_file.txt', f.write) # 二进制模式下载 # 或使用文本模式(适合ASCII文件) with open('local_file.txt', 'w') as f: ftp.retrlines('RETR remote_file.txt', f.write)
4. 文件上传
# 上传二进制文件 with open('local_file.zip', 'rb') as f: ftp.storbinary('STOR remote_file.zip', f) # 上传文本文件 with open('local_file.txt', 'r') as f: ftp.storlines('STOR remote_file.txt', f)
5. 其他常用操作
# 创建目录 ftp.mkd('new_directory') # 删除文件 ftp.delete('old_file.txt') # 删除目录 ftp.rmd('empty_directory') # 获取文件大小 size = ftp.size('large_file.zip') print(f"文件大小: {size}字节") # 重命名文件 ftp.rename('oldname.txt', 'newname.txt')
6. 关闭连接
ftp.quit() # 礼貌地关闭连接 # 或 ftp.close() # 直接关闭
实用技巧
1. 使用上下文管理器自动关闭连接
from ftplib import FTP with FTP('ftp.example.com') as ftp: ftp.login('username', 'password') ftp.cwd('/target_directory') # 执行操作... # 连接会自动关闭
2. 被动模式设置(解决防火墙问题)
ftp = FTP('ftp.example.com') ftp.set_pasv(True) # 启用被动模式(默认) ftp.login('username', 'password')
3. 下载进度显示
def download_with_progress(ftp, remote_file, local_file): def callback(data): file.write(data) print(f"\r已下载: {file.tell()}字节", end='') with open(local_file, 'wb') as file: ftp.retrbinary(f'RETR {remote_file}', callback) print() # 换行 # 使用 download_with_progress(ftp, 'large_file.iso', 'local_file.iso')
4. 递归下载整个目录
import os from ftplib import FTP def download_dir(ftp, remote_dir, local_dir): if not os.path.exists(local_dir): os.makedirs(local_dir) ftp.cwd(remote_dir) files = ftp.nlst() for file in files: local_path = os.path.join(local_dir, file) try: # 尝试作为文件下载 with open(local_path, 'wb') as f: ftp.retrbinary(f'RETR {file}', f.write) print(f"下载文件: {file}") except: # 如果是目录则递归下载 download_dir(ftp, file, local_path) ftp.cwd('..') # 返回上级目录 # 使用 download_dir(ftp, '/remote/path', './local_folder')
常见问题解决
-
连接超时:
from ftplib import FTP ftp = FTP(timeout=30) # 设置超时时间为30秒 ftp.connect('ftp.example.com')
-
UTF-8编码问题:
ftp.encoding = 'utf-8' # 设置编码
-
SSL/TLS加密连接:
from ftplib import FTP_TLS ftps = FTP_TLS('ftp.example.com') ftps.login('username', 'password') ftps.prot_p() # 切换到安全数据连接
-
大文件传输优化:
# 设置更大的缓冲区 ftp = FTP('ftp.example.com') ftp.login('username', 'password') ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8192) # 8KB缓冲区
完整示例 - FTP客户端
from ftplib import FTP import os class FTPClient: def __init__(self, host, username=None, password=None): self.ftp = FTP(host) self.ftp.login(username, password) print(f"已连接到 {host}") def list_files(self, path='.'): print(f"\n{path} 目录内容:") self.ftp.dir(path) def download(self, remote_file, local_file=None): if local_file is None: local_file = os.path.basename(remote_file) with open(local_file, 'wb') as f: self.ftp.retrbinary(f'RETR {remote_file}', f.write) print(f"\n文件 {remote_file} 已下载到 {local_file}") def upload(self, local_file, remote_file=None): if remote_file is None: remote_file = os.path.basename(local_file) with open(local_file, 'rb') as f: self.ftp.storbinary(f'STOR {remote_file}', f) print(f"\n文件 {local_file} 已上传为 {remote_file}") def close(self): self.ftp.quit() print("\n连接已关闭") if __name__ == "__main__": # 使用示例 ftp_client = FTPClient('ftp.example.com', 'username', 'password') try: ftp_client.list_files() ftp_client.download('README.txt') ftp_client.upload('localfile.txt') ftp_client.list_files() finally: ftp_client.close()

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)