標籤:文本 pat 列表 指令 open filename write word 而不是
1 # FTP操作 2 import ftplib 3 4 host = ‘192.168.20.191‘ 5 username = ‘ftpuser‘ 6 password = ‘ftp123‘ 7 file = ‘1.txt‘ 8 9 f = ftplib.FTP(host) # 執行個體化FTP對象10 f.login(username, password) # 登入11 12 # 擷取當前路徑13 pwd_path = f.pwd()14 print("FTP當前路徑:", pwd_path)15 16 17 # 逐行讀取ftp文字檔18 # f.retrlines(‘RETR %s‘ % file)19 20 def ftp_download():21 ‘‘‘以二進位形式下載檔案‘‘‘22 file_remote = ‘1.txt‘23 file_local = ‘D:\\test_data\\ftp_download.txt‘24 bufsize = 1024 # 設定緩衝器大小25 fp = open(file_local, ‘wb‘)26 f.retrbinary(‘RETR %s‘ % file_remote, fp.write, bufsize)27 fp.close()28 29 30 def ftp_upload():31 ‘‘‘以二進位形式上傳檔案‘‘‘32 file_remote = ‘ftp_upload.txt‘33 file_local = ‘D:\\test_data\\ftp_upload.txt‘34 bufsize = 1024 # 設定緩衝器大小35 fp = open(file_local, ‘rb‘)36 f.storbinary(‘STOR ‘ + file_remote, fp, bufsize)37 fp.close()38 39 40 ftp_download()41 ftp_upload()42 f.quit()43
FTP對象方法說明
- login(user=‘anonymous‘,passwd=‘‘, acct=‘‘) 登入 FTP 伺服器,所有參數都是可選的
- pwd() 獲得當前工作目錄
- cwd(path) 把當前工作目錄設定為 path 所示的路徑
- dir ([path[,...[,cb]]) 顯示 path 目錄裡的內容,可選的參數 cb 是一個回呼函數,會傳遞給 retrlines()方法
- nlst ([path[,...]) 與 dir()類似, 但返回一個檔案名稱列表,而不是顯示這些檔案名稱
- retrlines(cmd [, cb]) 給定 FTP命令(如“ RETR filename”),用於下載文字檔。可選的回呼函數 cb 用於處理檔案的每一行
- retrbinary(cmd,cb[,bs=8192[, ra]]) 與 retrlines()類似,只是這個指令處理二進位檔案。回呼函數 cb 用於處理每一塊(塊大小預設為 8KB)下載的資料
- storlines(cmd, f) 給定 FTP 命令(如“ STOR filename”),用來上傳文字檔。要給定一個檔案對象 f
- storbinary(cmd, f,[,bs=8192]) 與 storlines()類似,只是這個指令處理二進位檔案。要給定一個檔案對象 f,上傳塊大小 bs 預設為 8KB
- rename(old, new) 把遠程檔案 old 重新命名為 new
- delete(path) 刪除位元於 path 的遠程檔案
- mkd(directory) 建立遠程目錄
- rmd(directory) 刪除遠程目錄
- quit() 關閉串連並退出
python之FTP上傳和下載