這篇文章主要介紹了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文件,任務在後臺持續運行,不需要計劃任務,省心省力。
不用下載標記,一則較爲簡潔,二則本地文件如果被人誤刪或移動可自動重新下載。
日誌中,每天僅寫入任務啓動和文件已下載標誌,並記錄對應時間,如有需要可再添加。
希望能幫到有需要的朋友。
推薦我們的python學習基地,點擊進入,看老程序是如何學習的!從基礎的python腳本、爬蟲、django、數據挖掘等編程技術,工作經驗,還有前輩精心爲學習python的小夥伴整理零基礎到項目實戰的資料,!每天都有程序員定時講解Python技術,分享一些學習的方法和需要留意的小細節