一、概述

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

二、参数文件说明

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://files.cnblogs.com/files/ddzj01/filecopy.rar

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

Python - 文件分发小程序的更多相关文章

  1. 利用python实现微信小程序游戏跳一跳详细教程

    利用python实现微信小程序游戏跳一跳详细教程 1 先安装python 然后再安装pip <a href="http://newmiracle.cn/wp-content/uploa ...

  2. JWebFileTrans(JDownload): 一款可以从网络上下载文件的小程序(二)

    一  前言 本文是上一篇博客JWebFileTrans:一款可以从网络上下载文件的小程序(一)的续集.此篇博客主要在上一篇的基础上加入了断点续传的功能,用户在下载中途停止下载后,下次可以读取断点文件, ...

  3. JWebFileTrans(JDownload): 一款可以从网络上下载文件的小程序(三),多线程断点下载

    一 前言 本篇博客是<JWebFileTrans(JDownload):一款可以从网络上下载文件的小程序>系列博客的第三篇,本篇博客的内容主要是在前两篇的基础上增加多线程的功能.简言之,本 ...

  4. JDownload: 一款可以从网络上下载文件的小程序第四篇(整体架构描述)

    一 前言 时间过得真快,距离本系列博客第一篇的发布已经过去9个月了,本文是该系列的第四篇博客,将对JDownload做一个整体的描述与介绍.恩,先让笔者把记忆拉回到2017年年初,那会笔者在看Unix ...

  5. 【Python精华】100个Python练手小程序

    100个Python练手小程序,学习python的很好的资料,覆盖了python中的每一部分,可以边学习边练习,更容易掌握python. [程序1] 题目:有1.2.3.4个数字,能组成多少个互不相同 ...

  6. 整理了适合新手的20个Python练手小程序

    100个Python练手小程序,学习python的很好的资料,覆盖了python中的每一部分,可以边学习边练习,更容易掌握python. 本文附带基础视频教程:私信回复[基础]就可以获取的 [程序1] ...

  7. 微信小程序开发:python+sanic 实现小程序登录注册

    开发微信小程序时,接入小程序的授权登录可以快速实现用户注册登录的步骤,是快速建立用户体系的重要一步.这篇文章将介绍 python + sanic + 微信小程序实现用户快速注册登录全栈方案. 微信小程 ...

  8. Python编写购物小程序

    购物车要求: 用户名和密码存放于文件中 启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序 允许用户根据商品编号购买商品 用户选择商品后,检测余额是否够 ...

  9. [C#]Windows文件分类器小程序

    我平时习惯把各种文件都下载在`下载`文件夹中,时间久了,文件多了,想要找个文件就不那么方便了.于是我就想自己写一个小程序来实现下载文件的自动整理.我想到的文件分类方式是按照文件扩展名分类:把各文件移动 ...

随机推荐

  1. Spring面试题集锦(精选)

    以下来自网络收集,找不到原文出处.此次主要为了面试收集,希望对大家有所帮助~~~~ 1.什么是Spring? Spring是一个开源的Java EE开发框架.Spring框架的核心功能可以应用在任何J ...

  2. 个人搭建后台管理模板 Bootstrap4 ,ASP.NET Core,EF Core,JWT

    拥有一个美观好用的网站后台,是很多开发者的梦想,笔者在闲暇时间里搭建了一个不错的后台框架,这里分享诸位开发同仁. 项目地址:https://github.com/kongdf123/KentNoteB ...

  3. 【Python成长之路】Python爬虫 --requests库爬取网站乱码(\xe4\xb8\xb0\xe5\xa)的解决方法【华为云分享】

    [写在前面] 在用requests库对自己的CSDN个人博客(https://blog.csdn.net/yuzipeng)进行爬取时,发现乱码报错(\xe4\xb8\xb0\xe5\xaf\x8c\ ...

  4. 华为云ModelArts 2.0全面升级,革新传统AI开发模式

    [中国,上海,9月20日] 在HUAWEI CONNECT 2019期间,华为云EI服务产品部总经理贾永利宣布--华为云AI重装升级,并重磅发布一站式AI开发管理平台ModelArts 2.0. 现场 ...

  5. jQuery中detach&&remove&&empty三种方法的区别

    jQuery中empty&&remove&&detach三种方法的区别 empty():移除指定元素内部的所有内容,但不包括它本身 remove():移除指定元素内部的 ...

  6. mac查看开关机记录-last命令

    命令 last | grep reboot (查看开机时间记录) last | grep shutdown (查看关机时间记录) /var/log/messages日志中查询reboot(系统重启) ...

  7. Keras开发一个神经网络

    关于Keras:Keras是一个高级神经网络API,用Python编写,能够在TensorFlow,CNTK或Theano之上运行. 使用一下命令安装: pip install keras 在Kera ...

  8. python sympy evalf()函数

    SymPy是一个符号计算的Python库.它的目标是成为一个全功能的计算机代数系统,同时保持代码简 洁.易于理解和扩展.它完全由Python写成,不依赖于外部库.SymPy支持符号计算.高精度计算.模 ...

  9. Nginx的事件循环

    首先事件循环的起点就是监听端口获取连接,我们可以在ngx_event_core_module模块的ngx_event_process_init函数中看到如下的代码: /* for each liste ...

  10. 深入探讨多态性及其在Java中的好处

    多态是面向对象软件的基本原理之一.该术语通常表示可以具有多种形式的事物.在面向对象的方法中,多态使编写具有后期绑定引用的程序成为可能.尽管在Java中创建多态引用很容易,但其背后的概念对整体编程产生了 ...