要使用Python快速傳輸文件,可以使用ftplib
庫
from ftplib import FTP
def upload_file(local_file, remote_file, host, user, password):
# 連接到FTP服務器
ftp = FTP()
ftp.connect(host)
ftp.login(user, password)
ftp.set_pasv(True) # 被動模式
# 打開本地文件并上傳
with open(local_file, 'rb') as f:
ftp.storbinary(f'STOR {remote_file}', f)
# 斷開連接
ftp.quit()
# 使用示例
local_file = 'path/to/your/local/file.txt'
remote_file = 'path/to/your/remote/file.txt'
host = 'ftp.example.com'
user = 'your_username'
password = 'your_password'
upload_file(local_file, remote_file, host, user, password)
這個示例定義了一個名為upload_file
的函數,它接受本地文件路徑、遠程文件路徑、FTP服務器地址、用戶名和密碼作為參數。函數連接到FTP服務器,登錄并設置被動模式,然后打開本地文件并將其上傳到遠程服務器。最后,斷開連接。
請確保將示例中的變量替換為您自己的值。