1. 程式人生 > 程式設計 >Python FTP檔案定時自動下載實現過程解析

Python FTP檔案定時自動下載實現過程解析

這篇文章主要介紹了Python FTP檔案定時自動下載實現過程解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

一、需求:

  某資料公司每日15:00~17:00之間,在其FTP釋出當日資料供下載,我方需及時下載當日資料至指定本地目錄。

二、分析:

  1、需實現FTP登陸、查詢、下載功能;

  解答:使用內建的ftplib模組中FTP類;

  2、需判斷檔案是否下載;

  解答:使用os模組中path.exists方法;

  3、需判斷在指定時間段內才執行下載任務;

  解答:使用內建的time模組抓取當前時間,並與指定時間做比較;

  4、需考慮日期切換問題;

  解答:使用內建的time模組抓取當前日期,並與變數中的日期做比較。

三、程式碼實現

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

'''
@Time  : 2019-11-11 13:30
@Author : Peanut_C
@FileName: ftp_auto_download.py
'''


import time
from ftplib import FTP
import os


remote_path = "/xxx/yy/z/" # 遠端目錄
begin_time = 1500 # 任務開始時間
end_time = 1700 # 任務結束時間


today = time.strftime("%Y%m%d") # 當天日期
today_file = today + 'test.txt' # 得到當天日期的目標檔名
remote_file = remote_path + today_file # 遠端檔名
local_file = '\\\\local\\' + today + '\\' + today_file # 本地檔名
log_file = 'C:\\\\log\\ftp_log.txt'


def ftp_connect():
  """用於FTP連線"""
  ftp_server = 'w.x.y.z' # ftp站點對應的IP地址
  username = 'ftpuser' # 使用者名稱
  password = 'ftppass' # 密碼
  ftp = FTP()
  ftp.set_debuglevel(0) # 較高的級別方便排查問題
  ftp.connect(ftp_server,21)
  ftp.login(username,password)
  return ftp

def remote_file_exists():
  """用於FTP站點目標檔案存在檢測"""
  ftp = ftp_connect()
  ftp.cwd(remote_path) # 進入目標目錄
  remote_file_names = ftp.nlst() # 獲取檔案列表
  ftp.quit()
  if today_file in remote_file_names:
    return True
  else:
    return False

def download_file():
  """用於目標檔案下載"""
  ftp = ftp_connect()
  bufsize = 1024
  fp = open(local_file,'wb')
  ftp.set_debuglevel(0) # 較高的級別方便排查問題
  ftp.retrbinary('RETR ' + remote_file,fp.write,bufsize)
  fp.close()
  ftp.quit()


while True:
  if int(time.strftime("%H%M")) in range(begin_time,end_time): # 判斷是否在執行時間範圍
    if int(time.strftime("%Y%m%d")) - int(today) == 0: # 判斷是否跨日期
      while not os.path.exists(local_file): # 判斷本地是否已有檔案
        if remote_file_exists(): # 判斷遠端是否已有檔案
          download_file() 
          with open(log_file,'a') as f:
            f.write('\n' + time.strftime("%Y/%m/%d %H:%M:%S") + " 今日檔案已下載!")
          time.sleep(60) # 下載完畢靜默1分鐘
        else:
          time.sleep(180)
          break # 注意,此處跳出迴圈重新判斷日期,避免週末或當天沒檔案時陷入內層迴圈
      else:
        time.sleep(180)
    else:
      """如果跨日期,則根據當前日期,更新各檔案日期"""
      today = time.strftime("%Y%m%d") # 當天日期
      today_file = today + 'test.txt' # 得到當天日期的目標檔名
      remote_file = remote_path + today_file # 遠端檔名
      local_file = '\\\\local\\' + today + '\\' + today_file # 本地檔名
      with open(log_file,'a') as f:
        f.write('\n' + time.strftime("%Y/%m/%d %H:%M:%S") + " 任務啟動,檔案日期已更新。")
  else:
    time.sleep(1800)

四、執行情況

  儲存為pyw檔案,任務在後臺持續執行,不需要計劃任務,省心省力。

  不用下載標記,一則較為簡潔,二則本地檔案如果被人誤刪或移動可自動重新下載。

  日誌中,每天僅寫入任務啟動和檔案已下載標誌,並記錄對應時間,如有需要可再新增。

  希望能幫到有需要的朋友。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。