在Python中调用FTP服务器通常使用`ftplib`库。以下是一个基本的示例,展示了如何使用`ftplib`库连接到FTP服务器,下载文件,并关闭连接:
```python
from ftplib import FTP
连接到FTP服务器
ftp = FTP('ftp.example.com') 替换为你的FTP服务器地址
ftp.login(user='username', passwd='password') 替换为你的用户名和密码
切换到FTP服务器的指定目录
ftp.cwd('/path/to/ftp/directory') 替换为你的目录路径
列出FTP服务器当前目录下的文件
files = ftp.nlst()
下载FTP文件
for file in files:
local_file = open(file, 'wb') 在本地创建一个文件
ftp.retrbinary('RETR ' + file, local_file.write) 将FTP文件的内容写入本地文件中
local_file.close()
断开FTP连接
ftp.quit()
请根据你的实际情况替换FTP服务器地址、用户名、密码和目录路径。
如果你需要上传文件到FTP服务器,可以使用`storbinary`方法:
```python
从本地上传文件到FTP
def uploadfile(ftp, remotepath, localpath):
with open(localpath, 'rb') as fp:
ftp.storbinary('STOR ' + remotepath, fp)
使用这些函数时,请确保你已经安装了Python,并且`ftplib`库已经包含在内。