python FTP下载文件(python入门教程(非常详细))

网友投稿 1899 2022-09-06


python FTP下载文件(python入门教程(非常详细))

import datetimefrom ftplib import FTPimport os# local dirlocal_dir = 'E:/nwp_file/'# ftp infoftp_ip = '191.168.2.222'ftp_port = 21ftp_user_name = 'root'ftp_password = 'root'ftp_file_dir = '/home/ftp'# file infofile_prefix = 'MX_XBHFD_WF_'file_suffix = '06.txt'file_date_begin = '20220401'file_date_end = '20220430'file_date_format = '%Y%m%d'# download settingis_download_current_day = False# 判断本地文件夹是否存在,不存在则创建if not os.path.exists(local_dir): os.mkdir(local_dir)# 连接ftp = FTP()ftp.connect(ftp_ip, ftp_port)ftp.login(ftp_user_name, ftp_password)print('login ftp sunccess...')# cd到气象文件目录ftp.cwd(ftp_file_dir)# 打印目录# print(ftp.dir())# 遍历目录下所有文件for file_or_dir_name in ftp.nlst(): # print(file_or_dir_name) if file_or_dir_name.startswith(file_prefix) and file_or_dir_name.endswith(file_suffix): # 只下载当天文件 if is_download_current_day: cur_day = datetime.datetime.now().strftime(file_date_format) if cur_day in file_or_dir_name: new_file_path = local_dir + file_or_dir_name file_open = open(new_file_path, 'wb') ftp.retrbinary('RETR ' + file_or_dir_name, file_open.write) print('download file %s success...' % file_or_dir_name) # 下载指定日期范围 else: # 日期开始和结束时间 date_begin = datetime.datetime.strptime( file_date_begin, file_date_format) date_end = datetime.datetime.strptime( file_date_end, file_date_format) date_delta = datetime.timedelta(days=1) # 循环遍历日期范围,下载指定文件 while date_begin <= date_end: date_begin_str = date_begin.strftime(file_date_format) if date_begin_str in file_or_dir_name: new_file_path = local_dir + file_or_dir_name file_open = open(new_file_path, 'wb') ftp.retrbinary('RETR ' + file_or_dir_name, file_open.write) print('download file %s success...' % file_or_dir_name) date_begin += date_delta passprint('download finished...')# 关闭连接ftp.close()print('logout ftp sunccess...')


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:聊聊maven与jdk版本对应关系
下一篇:文本分词处理Python实践(python分词处理的函数)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~