python下载FTP文件
时间: 2024-09-18 08:10:38 浏览: 67
在Python中,你可以使用内置的ftplib模块来下载FTP文件。以下是一个简单的示例,说明如何连接到FTP服务器、登录并下载文件:
```python
import ftplib
def download_ftp_file(file_path, ftp_server, username, password):
# 创建FTP对象
ftp = ftplib.FTP(ftp_server)
# 登录FTP服务器
ftp.login(username, password)
try:
# 进入目标目录
ftp.cwd('/path/to/directory') # 替换为你需要进入的目录
# 下载文件
with open(file_path, 'wb') as local_file:
ftp.retrbinary('RETR %s' % file_path, local_file.write) # 文件名替换为你想要下载的文件名
print(f"文件 {file_path} 已成功下载")
finally:
# 关闭连接
ftp.quit()
# 调用函数,例如下载名为'downloaded_file.txt'的文件
download_ftp_file('downloaded_file.txt', 'your_server_address', 'your_username', 'your_password')
```
在这个例子中,你需要将`file_path`、`ftp_server`、`username`和`password`替换为你实际的FTP信息。如果成功,程序会打印出文件已成功下载的消息。
阅读全文
相关推荐


















