python從ftp獲取文件并下載到本地
最近有需求是,需要把對方提供的ftp地址上的圖片獲取到本地服務器,原先計劃想著是用shell 操作,因為shell 本身也支持ftp的命令 在通過for 循環也能達到需求。但是后來想著 還是拿python 操作;于是在網上進行百度;無一例外 還是那么失望 無法直接抄來就用。于是在一個代碼上進行修改。還是有點心東西學習到了;具體操作代碼如下 只要修改ftp 賬號密碼 已經對應目錄即可使用
在這需要注意一點的是os.path.join 的用法需要注意
#!/usr/bin/python# -*- coding: utf-8 -*-'''FTP常用操作'''from ftplib import FTPimport osclass FTP_OP(object): def __init__(self, host, username, password, port): ''' 初始化ftp :param host: ftp主機ip :param username: ftp用戶名 :param password: ftp密碼 :param port: ftp端口 (默認21) ''' self.host = host self.username = username self.password = password self.port = port def ftp_connect(self): ''' 連接ftp :return: ''' ftp = FTP() ftp.set_debuglevel(1) # 不開啟調試模式 ftp.connect(host=self.host, port=self.port) # 連接ftp ftp.login(self.username, self.password) # 登錄ftp ftp.set_pasv(False)##ftp有主動 被動模式 需要調整 return ftp def download_file(self, ftp_file_path, dst_file_path): ''' 從ftp下載文件到本地 :param ftp_file_path: ftp下載文件路徑 :param dst_file_path: 本地存放路徑 :return: ''' buffer_size = 102400 #默認是8192 ftp = self.ftp_connect() print(ftp.getwelcome() ) #顯示登錄ftp信息 file_list = ftp.nlst(ftp_file_path) for file_name in file_list: print('file_name'+file_name) ftp_file = os.path.join(ftp_file_path, file_name) print('ftp_file:'+ftp_file) #write_file = os.path.join(dst_file_path, file_name) write_file = dst_file_path+file_name ##在這里如果使用os.path.join 進行拼接的話 會丟失dst_file_path路徑,與上面的拼接路徑不一樣 print('write_file'+write_file) if file_name.find(’.png’)>-1 and not os.path.exists(write_file):print('file_name:'+file_name)#ftp_file = os.path.join(ftp_file_path, file_name)#write_file = os.path.join(dst_file_path, file_name)with open(write_file, 'wb') as f: ftp.retrbinary(’RETR %s’ % ftp_file, f.write, buffer_size) #f.close() ftp.quit()if __name__ == ’__main__’: host = '192.168.110.**' username = '****' password = '****' port = 21 ftp_file_path = '/erp-mall/' #FTP目錄 dst_file_path = '/root/11' #本地目錄 ftp = FTP_OP(host=host, username=username, password=password, port=port) ftp.download_file(ftp_file_path=ftp_file_path, dst_file_path=dst_file_path)
以上就是python從ftp獲取文件并下載到本地的詳細內容,更多關于python ftp下載文件的資料請關注好吧啦網其它相關文章!
相關文章: