在Python中,可以使用ftplib
庫來操作FTP服務器
from ftplib import FTP
# 連接到FTP服務器
ftp = FTP('ftp.example.com')
# 登錄
ftp.login(user='username', passwd='password')
# 切換到指定目錄
ftp.cwd('/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()
方法登錄到FTP服務器,使用cwd()
方法切換到指定目錄。接下來,我們定義了上傳文件、下載文件和列出目錄內容的函數。最后,我們使用quit()
方法退出FTP服務器。
請注意,這個示例僅用于演示目的,實際使用時需要根據你的需求進行修改。例如,你可能需要處理異常、設置傳輸模式(二進制或ASCII)等。