#!/usr/bin/python
# -*- coding: UTF-8 -*-
from ftplib import FTP
import sys
import time
import socket
import os
import pandas as pd
import datetimeclass MyFTP:"""ftp自动下载、自动上传脚本,可以递归目录操作"""def __init__(self, host, port=21):""" 初始化 FTP 客户端参数:host:ip地址port:端口号"""# print("__init__()---> host = %s ,port = %s" % (host, port))self.host = hostself.port = portself.ftp = FTP()# 重新设置下编码方式self.ftp.encoding = 'gbk'self.log_file = open("log.txt", "a")self.file_list = []def login(self, username, password):""" 初始化 FTP 客户端参数:username: 用户名password: 密码"""try:timeout = 60socket.setdefaulttimeout(timeout)# 0主动模式 1 #被动模式self.ftp.set_pasv(0)# 打开调试级别2,显示详细信息# self.ftp.set_debuglevel(2)# 解决中文乱码self.ftp.encoding = "utf-8"self.debug_print('开始尝试连接到 %s' % self.host)self.ftp.connect(self.host, self.port)self.debug_print('成功连接到 %s' % self.host)self.debug_print('开始尝试登录到 %s' % self.host)self.ftp.login(username, password)self.debug_print('成功登录到 %s' % self.host)self.debug_print(self.ftp.welcome)except Exception as err:self.deal_error("FTP 连接或登录失败 ,错误描述为:%s" % err)passdef is_same_size(self, local_file, remote_file):"""判断远程文件和本地文件大小是否一致参数:local_file: 本地文件remote_file: 远程文件"""try:remote_file_size = self.ftp.size(remote_file)except Exception as err:self.debug_print("is_same_size() 错误描述为:%s" % err)remote_file_size = -1try:local_file_size = os.path.getsize(local_file)except Exception as err:self.debug_print("is_same_size() 错误描述为:%s" % err)local_file_size = -1self.debug_print('local_file_size:%d  , remote_file_size:%d' % (local_file_size, remote_file_size))if remote_file_size == local_file_size:return 1else:return 0def download_file(self, local_file, remote_file):"""从ftp下载文件参数:local_file: 本地文件remote_file: 远程文件"""self.debug_print("download_file()---> local_path = %s ,remote_path = %s" % (local_file, remote_file))if self.is_same_size(local_file, remote_file):self.debug_print('%s 文件大小相同,无需下载' % local_file)returnelse:try:self.debug_print('>>>>>>>>>>>>下载文件 %s ... ...' % local_file)buf_size = 1024file_handler = open(local_file, 'wb')self.ftp.retrbinary('RETR %s' % remote_file, file_handler.write, buf_size)file_handler.close()except Exception as err:self.debug_print('下载文件出错,出现异常:%s ' % err)returndef download_file_tree(self, local_path, remote_path):"""从远程目录下载多个文件到本地目录参数:local_path: 本地路径remote_path: 远程路径"""print("download_file_tree()--->  local_path = %s ,remote_path = %s" % (local_path, remote_path))try:self.ftp.cwd(remote_path)except Exception as err:self.debug_print('远程目录%s不存在,继续...' % remote_path + " ,具体错误描述为:%s" % err)returnif not os.path.isdir(local_path):self.debug_print('本地目录%s不存在,先创建本地目录' % local_path)os.makedirs(local_path)self.debug_print('切换至目录: %s' % self.ftp.pwd())self.file_list = []# 方法回调self.ftp.dir(self.get_file_list)remote_names = self.file_listself.debug_print('远程目录 列表: %s' % remote_names)for item in remote_names:file_type = item[0]file_name = item[1]local = os.path.join(local_path, file_name)if file_type == 'd':print("download_file_tree()---> 下载目录: %s" % file_name)self.download_file_tree(local, file_name)elif file_type == '-':print("download_file()---> 下载文件: %s" % file_name)self.download_file(local, file_name)self.ftp.cwd("..")self.debug_print('返回上层目录 %s' % self.ftp.pwd())return Truedef upload_file(self, local_file, remote_file):"""从本地上传文件到ftp参数:local_path: 本地文件remote_path: 远程文件"""if not os.path.isfile(local_file):self.debug_print('%s 不存在' % local_file)returnif self.is_same_size(local_file, remote_file):self.debug_print('跳过相等的文件: %s' % local_file)returnbuf_size = 1024file_handler = open(local_file, 'rb')self.ftp.storbinary('STOR %s' % remote_file, file_handler, buf_size)file_handler.close()self.debug_print('上传: %s' % local_file + "成功!")def upload_file_tree(self, local_path, remote_path):"""从本地上传目录下多个文件到ftp参数:local_path: 本地路径remote_path: 远程路径"""if not os.path.isdir(local_path):self.debug_print('本地目录 %s 不存在' % local_path)returntry:self.ftp.cwd(remote_path)except:self.ftp.mkd(remote_path)self.ftp.cwd(remote_path)self.debug_print('切换至远程目录: %s' % self.ftp.pwd())local_name_list = os.listdir(local_path)for local_name in local_name_list:src = os.path.join(local_path, local_name)if os.path.isdir(src):try:self.ftp.mkd(local_name)except Exception as err:self.debug_print("目录已存在 %s ,具体错误描述为:%s" % (local_name, err))self.debug_print("upload_file_tree()---> 上传目录: %s" % local_name)self.upload_file_tree(src, local_name)else:self.debug_print("upload_file_tree()---> 上传文件: %s" % local_name)self.upload_file(src, local_name)self.ftp.cwd("..")def close(self):""" 退出ftp"""self.debug_print("close()---> FTP退出")self.ftp.quit()self.log_file.close()def debug_print(self, s):""" 打印日志"""self.write_log(s)def deal_error(self, e):""" 处理错误异常参数:e:异常"""log_str = '发生错误: %s' % eself.write_log(log_str)sys.exit()def write_log(self, log_str):""" 记录日志参数:log_str:日志"""time_now = time.localtime()date_now = time.strftime('%Y-%m-%d', time_now)format_log_str = "%s ---> %s \n " % (date_now, log_str)print(format_log_str)self.log_file.write(format_log_str)def get_file_list(self, line):""" 获取文件列表参数:line:"""file_arr = self.get_file_name(line)# 去除  . 和  ..if file_arr[1] not in ['.', '..']:self.file_list.append(file_arr)def get_file_name(self, line):""" 获取文件名参数:line:"""pos = line.rfind(':')while (line[pos] != ' '):pos += 1while (line[pos] == ' '):pos += 1file_arr = [line[0], line[pos:]]return file_arrdef check_up_erpdata(file_path,file无线超声波传感器,file无线工业测温传感器,yesterday,logging):result = os.listdir(file_path)df =pd.DataFrame({'filename':result})df1 =df[df.filename.str.contains(yesterday)]if df1.empty:# print('请及时上传ERP手工数据文件')logging = logging + '请催促客户及时传来ERP手工数据文件' + '\n'else:if len(df1)< 2:# print('请上传全部的ERP手工数据文件'+'已上传'+','.join(df1.filename.values))logging = logging + '请催促客户及时传来ERP手工数据文件,已传来:' + '\n' + ' <<==\n'.join(df1.filename.values)+'\n'else:if  file无线超声波传感器 in df1.filename.values and file无线工业测温传感器 in df1.filename.values :# print(file无线超声波传感器+'已上传')logging = logging + file无线超声波传感器+'已传来' + '\n'df无线超声波传感器 = pd.read_excel(file_path+file无线超声波传感器)if len(df无线超声波传感器['日期'].unique())==1:if df无线超声波传感器['日期'].unique().tolist()[0] == yesterday :# print(file无线超声波传感器+'文件内时间正确')logging = logging + file无线超声波传感器+'文件内时间正确' + '\n'else :# print('请检查文件内时间'+file无线超声波传感器)logging = logging + '请检查文件内时间'+file无线超声波传感器 +'\n'else :# print('请检查文件内时间'+file无线超声波传感器)logging = logging + '请检查文件内时间' + file无线超声波传感器 + '\n'# print(file无线工业测温传感器+'已上传')logging = logging + file无线工业测温传感器 + '已传来' + '\n'df无线工业测温传感器 = pd.read_excel(file_path+file无线工业测温传感器)if len(df无线工业测温传感器['日期'].unique())==1:if df无线工业测温传感器['日期'].unique().tolist()[0] == yesterday :# print(file无线工业测温传感器+'文件内时间正确')logging = logging + file无线工业测温传感器 + '文件内时间正确' + '\n'else :# print('请检查文件内时间'+file无线工业测温传感器)logging = logging + '请检查文件内时间' + file无线工业测温传感器 + '\n'else :# print('请检查文件内时间'+file无线工业测温传感器)logging = logging + '请检查文件内时间' + file无线工业测温传感器 + '\n'else :# print('请检查文件名字----上传的文件名: '+','.join(df1.filename.values))logging = logging + '请检查文件名字----已传来的文件名: ' + '\n' + ' <<==\n'.join(df1.filename.values) + '\n'return loggingdef check_up_reportdata(file_path,file无线超声波传感器,file无线工业测温传感器,yesterday,logging):result = os.listdir(file_path)df =pd.DataFrame({'filename':result})df1 =df[df.filename.str.contains(yesterday)]if df1.empty:# print('请及时上传人工数据文件')logging = logging + '催促客户及时传来人工数据文件' + '\n'else:if len(df1)< 2:# print('请上传全部的人工数据文件'+'已上传'+','.join(df1.filename.values))logging = logging + '催促客户及时传来人工数据文件,已传来:' + '\n' + ' <<==\n'.join(df1.filename.values)+'\n'else:if  file无线超声波传感器 in df1.filename.values and file无线工业测温传感器 in df1.filename.values :# print(file无线超声波传感器+'已上传')logging = logging + file无线超声波传感器 + '已传来' + '\n'df无线超声波传感器 = pd.read_excel(file_path+file无线超声波传感器)if len(df无线超声波传感器['当日日期'].unique())==1:if df无线超声波传感器['当日日期'].apply(lambda x:x.strftime('%Y-%m-%d')).unique().tolist()[0] == yesterday and (df无线超声波传感器['采集时间'].apply(lambda x:x.strftime('%Y-%m-%d %H:%M:%S')) == today+' 08:00:01').all():# print(file无线超声波传感器+'文件内时间正确')logging = logging + file无线超声波传感器 + '文件内时间正确' + '\n'else :# print('请检查文件内时间'+file无线超声波传感器)logging = logging + '请检查文件内时间'+file无线超声波传感器 +'\n'else :# print('请检查文件内时间'+file无线超声波传感器)logging = logging + '请检查文件内时间' + file无线超声波传感器 + '\n'# print(file无线工业测温传感器+'已上传')logging = logging + file无线工业测温传感器 + '已传来' + '\n'df无线工业测温传感器 = pd.read_excel(file_path+file无线工业测温传感器)if len(df无线工业测温传感器['当日日期'].unique())==1:if df无线工业测温传感器['当日日期'].apply(lambda x:x.strftime('%Y-%m-%d')).unique().tolist()[0] == yesterday and (df无线工业测温传感器['采集时间'].apply(lambda x:x.strftime('%Y-%m-%d %H:%M:%S')) == today+' 08:00:00').all() :# print(file无线工业测温传感器+'文件内时间正确')logging = logging + file无线工业测温传感器 + '文件内时间正确' + '\n'else :# print('请检查文件内时间'+file无线工业测温传感器)logging = logging + '请检查文件内时间' + file无线工业测温传感器 + '\n'else :# print('请检查文件内时间'+file无线工业测温传感器)logging = logging + '请检查文件内时间' + file无线工业测温传感器 + '\n'else :# print('请检查文件名字----上传的文件名: '+','.join(df1.filename.values))logging = logging + '请检查文件名字----已传来的文件名: ' + '\n' + ' <<==\n'.join(df1.filename.values) + '\n'return loggingif __name__ == "__main__":today = (datetime.datetime.now() - datetime.timedelta(days=0)).strftime('%Y-%m-%d')month = (datetime.datetime.now() - datetime.timedelta(days=0)).strftime('%Y-%m')yesterday = (datetime.datetime.strptime(today, '%Y-%m-%d') - datetime.timedelta(days=1)).strftime('%Y-%m-%d')erpdata_path = '/erpdata/'reportdata_path = '/reportdata/'local_base_path = "E:\\360MoveData\\Users\\Wu\\Documents\\WeChat Files\\daq-iot.top\\FileStorage\\File\\"erpdatafile无线超声波传感器 = 'ERP无线数据采集终端020无线超声波传感器欣欣_' + yesterday + '.xls'erpdatafile无线工业测温传感器 = '4Gwifi定时拍照相机0依依_' + yesterday + '.xlsx'reportdata无线超声波传感器 = '人工数据微功耗无线红外抄器欣欣_' + yesterday + '.xls'reportdata无线工业测温传感器 = '微功耗无线电流传感器020无线工业测温传感器依依_' + yesterday + '.xls'logging = ""try:erpdata_logging = check_up_erpdata(local_base_path+month+"\\", erpdatafile无线超声波传感器, erpdatafile无线工业测温传感器, yesterday, logging)logging = logging+erpdata_loggingreportdata_logging = check_up_reportdata(local_base_path+month+"\\", reportdata无线超声波传感器, reportdata无线工业测温传感器, yesterday, logging)logging = reportdata_loggingexcept Exception as e :logging = logging+str(e)print(logging)print('文件检测完成')if '请' not in logging:print("logging")a = input("按任意键退出")print('开始上传')# 上传单个文件my_ftp = MyFTP("192.168.116.214")my_ftp.login("user", "123")my_ftp.upload_file(local_base_path + month + "\\" + erpdatafile无线超声波传感器, "/erpdata/" + erpdatafile无线超声波传感器)my_ftp.upload_file(local_base_path + month + "\\" + erpdatafile无线工业测温传感器, "/erpdata/" + erpdatafile无线工业测温传感器)my_ftp.upload_file(local_base_path + month + "\\" + reportdata无线超声波传感器, "/reportdata/" + reportdata无线超声波传感器)my_ftp.upload_file(local_base_path + month + "\\" + reportdata无线工业测温传感器, "/reportdata/" + reportdata无线工业测温传感器)my_ftp.close()a=input("按任意键退出")

python 通过ftp自动 上传指定excel文件相关推荐

  1. python连接ftp并上传、下载文件

    # -*- coding:utf-8 -*- """ Created on 2019年12月11日 :封装FTP文件上传与下载函数 @author: dch " ...

  2. 文件已上传服务器去哪找,ftp文件服务器上传后的文件在哪

    ftp文件服务器上传后的文件在哪 内容精选 换一换 FTP/SFTP连接适用于从线下文件服务器或ECS服务器上迁移文件到OBS或数据库.当前仅支持Linux操作系统的FTP 服务器.连接FTP或SFT ...

  3. java struts2 excel上传_文件上传下载——通过struts的FormFile上传单个excel文件

    通过struts的FormFile上传单个excel文件 思路: 1.通过struts的FormFile获取File(这个文件的路径是"客户端的选择的路径地址") 2.将客户端的文 ...

  4. YDOOK: Sanic: Python request post请求 上传照片或文件 详细具体步骤 亲测可用!

    YDOOK: Sanic: Python request post请求 上传照片或文件 详细具体步骤 亲测可用! ©YDOOK JYLin 1. 项目目录架构: Upload result: 上传结果 ...

  5. 如何在命令行中使用 ftp 命令上传和下载文件

    转摘:https://linux.cn/article-6746-1.html 本文中,介绍在 Linux shell 中如何使用 ftp 命令.包括如何连接 FTP 服务器,上传或下载文件以及创建文 ...

  6. springMVC从上传的Excel文件中读取数据

    示例:导入客户文件(Excle文件) 一.编辑customer.xlsx 二.在spring的xml文件设置上传文件大小 <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1 ...

  7. [CentOS Python系列] 二.pscp上传下载服务器文件及phantomjs安装详解

    从2014年开始,作者主要写了三个Python系列文章,分别是基础知识.网络爬虫和数据分析. Python基础知识系列:Pythonj基础知识学习与提升 Python网络爬虫系列:Python爬虫之S ...

  8. WebFlux上传下载Excel文件

    文章目录 前言 一.引入相关jar包 二.开发过程 1.Excel上传 1.1 导入参数绑定 1.2 导入功能实现 2. Excel下载 总结 前言 最近在做一个API网关产品,要开发一个API批量导 ...

  9. [转]python的requests发送/上传多个文件

    1.需要的环境 Python2.X Requests 库 2.单字段发送单个文件 在requests中发送文件的接口只有一种,那就是使用requests.post的files参数, 请求形式如下: u ...

最新文章

  1. java collections_【Java视频教程】day31-集合练习??
  2. ACE的接受器(Acceptor)和连接器(Connector):连接建立模式
  3. Android下常见终端模拟器和SSH客户端感受及几个Tips
  4. 工业镜头选型计算公式_变压器分接开关选型指南
  5. java long更大_java – 比Long.MAX_VALUE大的长度
  6. easyui源码翻译1.32--Droppable(放置)
  7. c语言超市收银台程序,超市收银电脑操作流程
  8. FlashBuilder找不到所需要的AdobeFlashPlayer调试器版本的解
  9. ioi 赛制_徐明宽IOI2017参赛总结及他的信息学竞赛之路
  10. GCC自带的一些builtin内建函数
  11. 路由交换技术-交换机vlan,trunk,access等配置,保证其连通性,telnet远程登陆配置,osf协议配置,默认路由。
  12. 今日早报,365资讯简报12条,热点新闻早知道
  13. SSH登录出现REMOTE HOST IDENTIFICATION HAS CHANGED故障的解决办法
  14. 2811: [Apio2012]Guard
  15. 用Django编写邮箱注册以及验证码
  16. java随机生成汉字
  17. 2020-12-15
  18. Day27~Day32
  19. JDK1.8新特性 Optional判空详解,简化判空操作
  20. 数据结构--简易图书管理模拟系统

热门文章

  1. 【面试 - 八股文】Linux 高频面试题,助你吊打面试官系列
  2. 螺栓校核matlab仿真
  3. TTL反相器和CMOS
  4. 快速提升网站排名_使用快排优化的方法
  5. 一款模拟养成类游戏的策划大纲
  6. 微软提出基于知识图谱的深度神经网络DKN用于新闻推荐
  7. cmd返回上一级和根目录
  8. Matlab R2020a + Yalmip + IBM ILOG CPLEX Optimization Studio V12.10
  9. UKF-MATLAB实现
  10. 微信小程序:校验真实姓名和身份证号