1. 程式人生 > 程式設計 >python從ftp獲取檔案並下載到本地

python從ftp獲取檔案並下載到本地

最近有需求是,需要把對方提供的ftp地址上的圖片獲取到本地伺服器,原先計劃想著是用shell 操作,因為shell 本身也支援ftp的命令 在通過for 迴圈也能達到需求。但是後來想著 還是拿python 操作;於是在網上進行百度;無一例外 還是那麼失望 無法直接抄來就用。於是在一個程式碼上進行修改。還是有點心東西學習到了;具體操作程式碼如下 只要修改ftp 賬號密碼 已經對應目錄即可使用

在這需要注意一點的是os.path.join 的用法需要注意

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
FTP常用操作
"""
from ftplib import FTP
import os
class 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下載檔案的資料請關注我們其它相關文章!