Python连接ftp服务器
时间: 2024-10-24 17:08:54 浏览: 26
python连接远程ftp服务器并列出目录下文件的方法
在Python中,你可以使用内置的`ftplib`模块来连接FTP服务器。以下是基本步骤:
1. 导入`ftplib`模块:
```python
import ftplib
```
2. 创建FTP对象并连接到服务器:
```python
def connect_to_ftp(host, username, password):
ftp = ftplib.FTP(host)
ftp.login(user=username, passwd=password)
return ftp
# 使用示例
ftp_instance = connect_to_ftp("your_server_address", "your_username", "your_password")
```
3. 操作FTP服务器(如上传、下载文件,列出目录等):
- 上传文件:
```python
def upload_file(ftp, local_file_path, remote_file_path):
with open(local_file_path, 'rb') as file:
ftp.storbinary('STOR ' + remote_file_path, file)
```
- 下载文件:
```python
def download_file(ftp, remote_file_path, local_file_path):
ftp.retrbinary('RETR ' + remote_file_path, open(local_file_path, 'wb').write)
```
- 列出目录:
```python
def list_files(ftp, directory):
files = ftp.nlst(directory)
return files
```
4. 断开连接:
```python
ftp.quit()
```
阅读全文