Python實現FTP文件定時自動下載


  之前遇到技術問題總能在技術博客上得到啟發,十分感謝各位的無私分享。而自己卻很少發文,固然是水平有限,但也限制了知識積累和總結。今后多總結分享,回饋博客的同時也希望大家多多批評。

 

一、需求:

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

 

二、分析:

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

  解答:使用內置的ftplib模塊中FTP類;

 

  2、需判斷文件是否下載;

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

 

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

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

 

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

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

 

三、代碼實現

 1 #!/usr/bin/env python
 2 # _*_ coding:utf-8 _*_
 3 
 4 '''
 5 @Time    : 2019-11-11 13:30
 6 @Author  : Peanut_C
 7 @FileName: ftp_auto_download.py
 8 '''
 9 
10 
11 import time
12 from ftplib import FTP
13 import os
14 
15 
16 remote_path = "/xxx/yy/z/"  # 遠端目錄
17 begin_time = 1500  # 任務開始時間
18 end_time = 1700  # 任務結束時間
19 
20 
21 today = time.strftime("%Y%m%d")  # 當天日期
22 today_file = today + 'test.txt'  # 得到當天日期的目標文件名
23 remote_file = remote_path + today_file  # 遠端文件名
24 local_file = '\\\\local\\' + today + '\\' + today_file  # 本地文件名
25 log_file = 'C:\\\\log\\ftp_log.txt'
26 
27 
28 def ftp_connect():
29     """用於FTP連接"""
30     ftp_server = 'w.x.y.z'  # ftp站點對應的IP地址
31     username = 'ftpuser'  # 用戶名
32     password = 'ftppass'  # 密碼
33     ftp = FTP()
34     ftp.set_debuglevel(0) # 較高的級別方便排查問題
35     ftp.connect(ftp_server, 21)
36     ftp.login(username, password)
37     return ftp
38 
39 def remote_file_exists():
40     """用於FTP站點目標文件存在檢測"""
41     ftp = ftp_connect()
42     ftp.cwd(remote_path) # 進入目標目錄
43     remote_file_names = ftp.nlst()  # 獲取文件列表
44     ftp.quit()
45     if today_file in remote_file_names:
46         return True
47     else:
48         return False
49 
50 def download_file():
51     """用於目標文件下載"""
52     ftp = ftp_connect()
53     bufsize = 1024
54     fp = open(local_file, 'wb')
55     ftp.set_debuglevel(0) # 較高的級別方便排查問題
56     ftp.retrbinary('RETR ' + remote_file, fp.write, bufsize)
57     fp.close()
58     ftp.quit()
59 
60 
61 while True:
62     if int(time.strftime("%H%M")) in range(begin_time, end_time):  # 判斷是否在執行時間范圍
63         if int(time.strftime("%Y%m%d")) - int(today) == 0:  # 判斷是否跨日期
64             while not os.path.exists(local_file):  # 判斷本地是否已有文件
65                 if remote_file_exists():  # 判斷遠端是否已有文件
66                     download_file() 
67                     with open(log_file, 'a') as f:
68                         f.write('\n' + time.strftime("%Y/%m/%d %H:%M:%S") + " 今日文件已下載!")
69                     time.sleep(60)  # 下載完畢靜默1分鍾
70                 else:
71                     time.sleep(180)
72                     break # 注意,此處跳出循環重新判斷日期,避免周末或當天沒文件時陷入內層循環
73             else:
74                 time.sleep(180)
75         else:
76             """如果跨日期,則根據當前日期,更新各文件日期"""
77             today = time.strftime("%Y%m%d")  # 當天日期
78             today_file = today + 'test.txt'  # 得到當天日期的目標文件名
79             remote_file = remote_path + today_file  # 遠端文件名
80             local_file = '\\\\local\\' + today + '\\' + today_file  # 本地文件名
81             with open(log_file, 'a') as f:
82                 f.write('\n' + time.strftime("%Y/%m/%d %H:%M:%S") + " 任務啟動, 文件日期已更新。")
83     else:
84         time.sleep(1800)

 

四、運行情況

  保存為pyw文件,任務在后台持續運行,不需要計划任務,省心省力。

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

  日志中,每天僅寫入任務啟動和文件已下載標志,並記錄對應時間,如有需要可再添加。

 

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

 

  多多指教!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM