在Python中,可以使用第三方庫ftplib
和tqdm
來查看FTP傳輸進度。以下是一個示例代碼:
首先,確保已經安裝了tqdm
庫。如果沒有安裝,可以使用以下命令安裝:
pip install tqdm
然后,使用以下代碼實現FTP文件傳輸并顯示進度:
from ftplib import FTP
from tqdm import tqdm
import os
def ftp_upload(local_file, remote_file):
# 連接到FTP服務器
ftp = FTP('ftp.example.com')
ftp.login(user='username', passwd='password')
ftp.set_pasv(True) # 被動模式
# 打開本地文件
with open(local_file, 'rb') as f:
# 上傳文件并顯示進度
ftp.storbinary(f'STOR {remote_file}', tqdm(f, unit='B', unit_scale=True, desc=local_file))
# 關閉連接
ftp.quit()
# 使用示例
local_file = 'path/to/local/file.txt'
remote_file = 'path/to/remote/file.txt'
ftp_upload(local_file, remote_file)
在這個示例中,我們定義了一個名為ftp_upload
的函數,它接受本地文件路徑和遠程文件路徑作為參數。我們使用ftplib
庫連接到FTP服務器,并使用tqdm
庫創建一個進度條。storbinary
方法用于上傳文件,同時tqdm
庫會自動更新進度條。
請注意,您需要將示例代碼中的ftp.example.com
、username
和password
替換為您自己的FTP服務器信息。