python的FTP模組

來源:互聯網
上載者:User

標籤:

python本身內建一個FTP模組,可以輕鬆實現FTP的上傳,下載等操作。下面來看看用法:

from ftplib import FTPimport socket    #用來設定逾時時間FTP.connect(伺服器位址,連接埠,逾時時間)      # 串連伺服器FTP.login(使用者名稱,使用者密碼)        # 使用者登入FTP.pwd(路徑)                    # 讀取操作路徑FTP.cwd(路徑)                    # 設定要操作FTP檔案夾路徑FTP.nlst()            # 獲得目錄下檔案FTP.retrbinary(檔案名稱, 回呼函數)     # 下載FTP上的檔案FTP.delete(檔案名稱)                # 刪除FTP檔案FTP.storbinary(檔案名稱, 檔案對象 [,塊大小])     # 上傳FTP檔案FTP.quit()                      # 退出FTP伺服器FTP.set_pasv(boolean)           # 是否設定為被動模式 FTP.rename(old, new)            # 重新命名FTP.delete(path)                # 刪除檔案FTP.mkd(directory)              # 建立目錄

 

一個上傳代碼:

import socketfrom ftplib import FTPftp_server=‘xx.xx.xx.xx‘ftp_user=‘xxxxx‘ftp_password=‘xxxxx‘ftp_backup_dir=‘backup‘ newday = date.today()    #擷取今天的日期oldday = date.today()-timedelta(5)    #獲得5天前的日期newfile = ‘/home/backup/‘ + ‘backup_data_‘ + str(newday.year) + ‘.‘ + str(newday.month) + ‘.‘ +  str(newday.day) + ‘.zip‘    #本次備份檔案名(絕對路徑)oldfile = ‘/home/backup/‘ + ‘backup_data_‘ + str(oldday.year) + ‘.‘ + str(oldday.month) + ‘.‘ +  str(oldday.day) + ‘.zip‘    #5天前備份的檔案名稱(絕對路徑) def upload():    socket.setdefaulttimeout(60)    #逾時FTP時間設定為60秒    ftp = FTP(ftp_server)    print("login ftp...")    try:        ftp.login(ftp_user, ftp_password)        print(ftp.getwelcome())   #獲得歡迎資訊         try:            if ftp_backup_dir in ftp.nlst():                print("found backup folder in ftp server, upload processing.")            else:                print("don‘t found backup folder in ftp server, try to build it.")                ftp.mkd(ftp_backup_dir)        except:            print("the folder" + ftp_backup_dir + "doesn‘t exits and can‘t be create!")            sys.exit()    except:        print("ftp login failed.exit.")        sys.exit()    ftp.cwd(ftp_backup_dir)    #設定FTP路徑     print("upload data...")    try:        ftp.storbinary(‘STOR ‘ + os.path.basename(newfile), open(newfile,‘rb‘), 1024)    #上傳備份檔案    except:        print("upload failed. check your permission.")        print("delte old file...")    try:        ftp.delete(os.path.basename(oldfile))    #刪除5天前的備份檔案    except:        print("the old file in ftp doesn‘t exists, jumped.")     print("ftp upload successful.exit...")    ftp.quit() if __name__== ‘__main__‘:    upload()

樣本2:

  ftpserver = "192.168.0.1"

# 建立FTP串連
ftp = ftplib.FTP(ftpserver)
# FTP使用者驗證
ftp.login(‘administrator‘, ‘sunfast‘)
# 切換ftp操作目錄
ftp.cwd("/fromcovisint/094200005560743089CHN03_830")
for filename in ftp.nlst(): # 擷取ftp操作目錄的所有檔案
if os.path.splitext(filename)[1].upper() == ‘.CSV‘:
if ‘FINISHED‘ in filename:
continue
else:
try:
#下載指定檔案到當前操作目錄中
ftp.retrbinary(‘RETR %s‘ % filename, open(filename, ‘wb‘).write)
#ftp.storbinary(‘STOR %s‘% filename, open(filename, ‘rb‘), CONST_BUFFER_SIZE) FTP上傳檔案
# 匯入資料
self.import_data(os.path.join(os.getcwd(), filename))
new_filename = os.path.splitext(filename)[0] + "_FINISHED" + os.path.splitext(filename)[1]
# 修改FTP目錄上的檔案名稱,使用新的檔案名稱
ftp.rename(filename, new_filename)
finally:
# 刪除目前的目錄中下載的檔案明細
os.remove(os.path.join(os.getcwd(), filename))
ftp.quit()

參考文檔:

http://doublewei369.blog.163.com/blog/static/342947812012923113356945/

http://blog.csdn.net/wklken/article/details/7059423

http://wangwei007.blog.51cto.com/68019/983638

python的FTP模組

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.