Python中可以使用ftplib库来操作FTP服务器
from ftplib import FTP # 连接到FTP服务器 ftp = FTP('ftp.example.com') # 将'ftp.example.com'替换为你的FTP服务器地址 ftp.login(user='username', passwd='password') # 使用用户名和密码登录 # 切换到指定目录 ftp.cwd('/path/to/directory') # 将'/path/to/directory'替换为你想要切换到的目录路径 # 上传文件 def upload_file(local_file, remote_file): with open(local_file, 'rb') as f: ftp.storbinary(f'STOR {remote_file}', f) # 下载文件 def download_file(remote_file, local_file): with open(local_file, 'wb') as f: ftp.retrbinary(f'RETR {remote_file}', f.write) # 列出目录内容 def list_directory(): ftp.retrlines('LIST') # 退出FTP服务器 ftp.quit()
在这个示例中,我们首先导入了ftplib库并连接到了FTP服务器。然后,我们使用login()
方法登录到服务器,使用cwd()
方法切换到指定目录。接下来,我们定义了三个函数:upload_file()
用于上传文件,download_file()
用于下载文件,list_directory()
用于列出目录内容。最后,我们使用quit()
方法退出FTP服务器。
你可以根据自己的需求修改这个示例,例如使用不同的FTP服务器地址、用户名、密码和目录路径。