在气象领域,FTP是比较常用的一个数据来源。本文尝试采用python的ftplib包,实现了从指定ftp服务器中批量下载文件的功能。供大家学习参考。
https://docs.python.org/3/library/ftplib.html#module-ftplib 该网址为官方文档。
代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 11:05:38 2019
@author: BBR
"""
import ftplib
import os
import datetime
host = '172.18.16.30'
username = 'ww'
password = ''
localpath=r"\\10.226.110.225\Climate_Share\10.226.110.225\climates\data\file\a"
f = ftplib.FTP(host)
f.login(username, password)
nowstr=datetime.datetime.now()
lastmonth=nowstr-datetime.timedelta(weeks=1)
datestr=lastmonth.strftime('%Y%m')
f.cwd('clim')
pwd_path = f.pwd()
stationids=['A54428','A54525','A54523','A54529','A54619','A54527',\
'A54528','A54517','A54526','A54622','A54645','A54530','A54623']
stationnames=['蓟州','宝坻','武清','宁河','静海','西青',\
'北辰','市区','东丽','津南','大港','汉沽','塘沽']
def ftp_download(filename,stationname):
file_remote = filename
file_local = localpath+'\\'+filename
bufsize = 1024 # 设置缓冲器大小
try:
fp = open(file_local, 'wb')
f.retrbinary('RETR %s' % file_remote, fp.write, bufsize)
except:
fp.close()
os.remove(file_local)
print(stationname+' 文件不存在!')
fp.close()
for id,idname in zip(stationids,stationnames):
filename=id+'-'+datestr+'.TXT'
ftp_download(filename,idname)
f.quit()