python 写一个文件分发小程序


Posted in Python onDecember 05, 2020

一、概述

该小程序实现从源端到目标端的文件一键拷贝,源端和目标段都在一台电脑上面,只是目录不同而已

二、参数文件说明

1. settings.txt的说明
a. 通过配置settings.txt,填源端和目标端路径,如果用反斜杠结尾表示填的是文件夹,如果不是反斜杠结尾则代表填的是文件
b. 如果是按日期自动生成的文件夹,则用{YYYYMMMDD}或{MMDD}等替代
c. 文件支持*匹配任意名字
d. 在no_create_ok_file组中,表示不生成ok标识,在create_ok_file组中表示生成ok标识
e. 如果settings.txt填写不正确,运行这个小程序就会生成一个error.log,但是不影响后面的拷贝

举例
D:\test3\{YYYYMMDD}\ = E:\test4\{YYYYMMDD}\,如果在执行程序的时候不填日期,直接回车,这个{YYYYMMDD}就自动替换为当天的日期,如果填了日期(如20191115),那{YYYYMMDD}就自动替换为20191115
D:\test1\fa* = E:\test2\,这个就表示把D:\test1目录下的以fa开头的文件全部拷贝到E:\test2中去

2. okfile.txt的说明
okfile.txt填的源端的ok文件,有些系统在生成文件的时候,会生成一个ok文件,表示系统文件已经生成完成。okfile.txt就是来校验这些文件是否存在,如果不存在,那么运行这个小程序的时候就会生成一个warn.log,但是不影响实际的拷贝。

三、程序说明

由于业务人员不懂python,也没有装开发环境,因此通过将python文件打包成一个exe的形式,方便他们操作。

pip isntall PyInstaller # 安装PyInstaller包
pyinstaller -F filetran.py --icon=rocket.ico # 将.py文件和.ico文件放在一起,在dist目录下面生成exe文件

由于我的py文件需要读这两个配置文件,因此还需要将.exe文件和这两个配置文件放在同一个目录下面,就可以到任意一台windows下面执行了

四、附上代码
filetran.py

# autor: yangbao
# date: 2019-10-16
import os
import time
import datetime
import re
import shutil
import configparser


def variable_replace(variable):
 """路径替换"""
 global customer_input
 local_customer_input = customer_input
 if local_customer_input:
 curr_year = local_customer_input[0:4]
 curr_month = local_customer_input[4:6]
 curr_day = local_customer_input[6:8]
 else:
 curr_year = str(time.strftime('%Y'))
 curr_month = str(time.strftime('%m'))
 curr_day = str(time.strftime('%d'))
 if re.search('{YYYYMMDD}', variable):
 variable = variable.replace('{YYYYMMDD}', curr_year+curr_month+curr_day)
 if re.search('{YYYYMM}', variable):
 variable = variable.replace('{YYYYMM}', curr_year+curr_month)
 if re.search('{MMDD}', variable):
 variable = variable.replace('{MMDD}', curr_month+curr_day)
 if re.search('{YYYY}', variable):
 variable = variable.replace('{YYYY}', curr_year)
 if re.search('{MM}', variable):
 variable = variable.replace('{MM}', curr_month)
 if re.search('{DD}', variable):
 variable = variable.replace('{DD}', curr_day)
 return variable


def source_to_target():
 """读取settings.txt文件,将源端和目标端映射关系对上"""
 source_to_target_dict = {}
 with open('settings.txt', 'r', encoding='utf-8-sig') as f:
 for line in f.readlines():
 # 排除注释和空行和格式不正确的
 if not line.startswith('#') and line.strip() != '' and re.search('=', line):
 source = line.split('=')[0].strip()
 target = line.split('=')[1].strip()
 source_to_target_dict[source] = target
 return source_to_target_dict


def create_ok_file(source):
 """读取配置文件"""
 cf = configparser.ConfigParser(delimiters=('='))
 cf.read("settings.txt", encoding='utf-8-sig')
 options = cf.options("create_ok_file")
 for i in options:
 if source.lower() == i.lower().strip():
 return True
 return False


def filecopy():
 """文件拷贝"""

 # 得到映射表
 source_to_target_dict = source_to_target()

 # 读取每一个目标路径
 for ori_source, ori_target in source_to_target_dict.items():

 source = variable_replace(ori_source)
 target = variable_replace(ori_target)

 # 如果源端填的是文件夹
 if source.endswith(os.sep):
 if os.path.exists(source):
 file_list = os.listdir(source)
 for filename in file_list:
 # 如果目标路径不存在,就创建
 if not os.path.exists(target):
 os.makedirs(target)
 source_file = source + filename
 target_file = target + filename
 print('[', time.strftime('%Y-%m-%d %H:%M:%S'), '] ', source_file, ' ----> ', target_file, ' 开始拷贝', sep='')
 try:
 shutil.copyfile(source_file, target_file)
 if create_ok_file(ori_source):
 ok_file = target_file + '.ok'
 fp = open(ok_file, 'w')
 fp.close()
 except Exception as e:
 with open(error_log_name, 'a+', encoding='utf-8-sig') as f:
 f.write(str(e))
 f.write('\n')
 break
 # print('[', time.strftime('%Y-%m-%d %H:%M:%S'), '] ', source_file, ' ----> ', target_file, ' 拷贝完成', sep='')
 # 如果源端填的是文件
 else:
 source_dir = source[0:source.rfind(os.sep)+1] # 得到该文件所在的文件夹
 file_name_pattern = source[source.rfind(os.sep)+1:] # 得到该文件的文件样式
 if os.path.exists(source_dir):
 file_list = os.listdir(source_dir)
 for filename in file_list:
 # 只有匹配上的才拷贝
 if re.match(file_name_pattern, filename):
 # 如果目标路径不存在,就创建
 if not os.path.exists(target):
 os.makedirs(target)
 source_file = source_dir + filename
 target_file = target + filename
 print('[', time.strftime('%Y-%m-%d %H:%M:%S'), '] ', source_file, ' ----> ', target_file, ' 开始拷贝', sep='')
 try:
 shutil.copyfile(source_file, target_file)
 if create_ok_file(ori_source):
 ok_file = target_file + '.ok'
 fp = open(ok_file, 'w')
 fp.close()
 except Exception as e:
 with open(error_log_name, 'a+', encoding='utf-8-sig') as f:
 f.write(str(e))
 f.write('\n')
 break
 # print('[', time.strftime('%Y-%m-%d %H:%M:%S'), '] ', source_file, ' ----> ', target_file, ' 拷贝完成', sep='')


def warnlog():
 """警告日志"""
 with open('okfile.txt', 'r', encoding='utf-8') as f:
 for line in f.readlines():
 # 排除注释和空行和格式不正确的
 if not line.startswith('#') and line.strip() != '':
 okfile = variable_replace(line.strip())
 if not os.path.isfile(okfile):
 with open(warn_log_name, 'a+', encoding='utf-8-sig') as t:
 t.write(okfile + ' 该文件不存在!')
 t.write('\n')


if __name__ == '__main__':
 # 主程序
 customer_input = input('请输入需要拷贝的8位指定日期,如20191114,如果不输入,默认拷贝当天\n')
 # 如果没输入,或者输入格式正确,就拷贝
 if re.match('\d{8}',customer_input) or not customer_input:
 begin_time = datetime.datetime.now()
 error_log_name = 'error_' + str(time.strftime('%Y%m%d_%H%M%S')) + '_.log'
 warn_log_name = 'warn_' + str(time.strftime('%Y%m%d_%H%M%S')) + '_.log'
 print('[', time.strftime('%Y-%m-%d %H:%M:%S'), '] ', '文件开始拷贝...', sep='')
 print('-' * 50)
 filecopy()
 warnlog()
 end_time = datetime.datetime.now()
 cost_time = (end_time - begin_time).seconds
 print('-' * 50)
 print('[', time.strftime('%Y-%m-%d %H:%M:%S'), '] ', '文件拷贝结束,总耗时', cost_time, '秒', sep='')
 # 如果输入格式不正确
 elif not re.match('\d{8}', customer_input):
 print('请输入正确的格式')
 input('按回车键退出')

settings.txt 

# 拷贝路径设置
# 源端路径不存在就不复制,目标端路径不存在会自动创建目录
# 说明事项:
# 1. 格式为源端路径 = 目标路径
# 2. 文件夹后面以反斜杠结束\
# 3. 如果是变量,则以大括号阔起来,如今天是20191012, {YYYYMMDD}会替换为20191012,则使用{MMDD}替换为1012,{DD}替换为12
# 4. YYYY MM DD都填大写
# 以下是示例
# 拷贝整个文件夹 --> P:\信息技术部\YangBao\oa\ = E:\test2\
# 拷贝指定名称,*表示匹配任意字符 --> D:\test3\{YYYYMMDD}\ab* = E:\test4\{YYYYMMDD}\

[no_create_ok_file]
# 将不需要生成ok标识的路径或文件填在这下面

D:\test3\{YYYYMMDD}\ = E:\test4\{YYYYMMDD}\


[create_ok_file]
# 将需要生成ok标识的路径或文件填在这下面

D:\test1\ = E:\test2\

okfile.txt

# ok文件设置设置
# 以下是示例
# {YYYYMMDD}会替换成指定日期,D:\test3\{YYYYMMDD}\ab.txt

# D:\test3\{YYYYMMDD}\sdfg

filetran.exe

https://pan.baidu.com/s/1vxO6UycDtz5nN4DpmjLN5w   提取码:bgdu

注意不管是使用python去执行filetran.py,还是单击filetran.exe,都需要跟settings.txt和okfile.txt放在一起,否则程序会报错。

以上就是python 写一个文件分发小程序的详细内容,更多关于python 文件分发的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
浅析Python中的多进程与多线程的使用
Apr 07 Python
Python判断列表是否已排序的各种方法及其性能分析
Jun 20 Python
使用python调用zxing库生成二维码图片详解
Jan 10 Python
Python实现求笛卡尔乘积的方法
Sep 16 Python
python 实现提取某个索引中某个时间段的数据方法
Feb 01 Python
python整合ffmpeg实现视频文件的批量转换
May 31 Python
Python Pillow.Image 图像保存和参数选择方式
Jan 09 Python
Pandas时间序列基础详解(转换,索引,切片)
Feb 26 Python
Python 字符串池化的前提
Jul 03 Python
Python爬虫实例之2021猫眼票房字体加密反爬策略(粗略版)
Feb 22 Python
Python socket如何解析HTTP请求内容
Feb 12 Python
python三子棋游戏
May 04 Python
解决Pymongo insert时会自动添加_id的问题
Dec 05 #Python
用python对oracle进行简单性能测试
Dec 05 #Python
python mongo 向数据中的数组类型新增数据操作
Dec 05 #Python
python自动从arxiv下载paper的示例代码
Dec 05 #Python
python使用dlib进行人脸检测和关键点的示例
Dec 05 #Python
python从ftp获取文件并下载到本地
Dec 05 #Python
python基于socket模拟实现ssh远程执行命令
Dec 05 #Python
You might like
PHPWind 发帖回帖Api PHP版打包下载
2010/02/08 PHP
php读取图片内容并输出到浏览器的实现代码
2013/08/08 PHP
PHP获取网页标题的3种实现方法代码实例
2014/04/11 PHP
浅谈discuz密码加密的方式
2014/05/22 PHP
在Ubuntu 14.04上部署 PHP 环境及 WordPress
2014/09/02 PHP
php实现根据身份证获取精准年龄
2020/02/26 PHP
Prototype 1.5.0_rc1 及 Prototype 1.5.0 Pre0小抄本
2006/09/22 Javascript
js 编码转换 gb2312 和 utf8 互转的2种方法
2013/08/07 Javascript
JS 操作Array数组的方法及属性实例解析
2014/01/08 Javascript
JavaScript获取flash对象与网上的有所不同
2014/04/21 Javascript
js与C#进行时间戳转换
2014/11/14 Javascript
jquery通过load获取文件的内容并跳到锚点的方法
2015/01/29 Javascript
JS实现仿中关村论坛评分后弹出提示效果的方法
2015/02/23 Javascript
jQuery实现鼠标经过提示信息的地图热点效果
2015/04/26 Javascript
浅谈时钟的生成(js手写简洁代码)
2016/08/20 Javascript
探讨跨域请求资源的几种方式(总结)
2016/12/02 Javascript
node.JS md5加密中文与php结果不一致的解决方法
2017/05/05 Javascript
JavaScript callback回调函数用法实例分析
2018/05/08 Javascript
vue: WebStorm设置快速编译运行的方法
2018/10/18 Javascript
vue+Element实现搜索关键字高亮功能
2019/05/28 Javascript
JS实现点击发送验证码 xx秒后重新发送功能
2019/07/30 Javascript
Vue js with语句原理及用法解析
2020/09/03 Javascript
js屏蔽F12审查元素,禁止修改页面代码等实现代码
2020/10/02 Javascript
python3+PyQt5使用数据库窗口视图
2018/04/24 Python
给我一面国旗 python帮你实现
2019/09/30 Python
pytorch-RNN进行回归曲线预测方式
2020/01/14 Python
Python super()函数使用及多重继承
2020/05/06 Python
意大利奢侈品购物网站:Deliberti
2019/10/08 全球购物
大学生自荐书范文
2013/12/10 职场文书
会计电算化专业毕业生自荐信
2013/12/20 职场文书
怎样写好自荐信和推荐信
2013/12/26 职场文书
工作散漫检讨书
2014/09/16 职场文书
《卖火柴的小女孩》教学反思
2016/02/19 职场文书
2016年小学六一儿童节活动总结
2016/04/06 职场文书
推荐六本经典文学奖书籍:此生必读
2019/08/22 职场文书
JavaScript中reduce()的用法
2022/05/11 Javascript