python to write a file distribution applet
- 2021-08-17 00:16:17
- OfStack
1. Overview
This small program realizes the file 1 key copy from the source end to the target end, the source end and the target segment are all on 1 computer, but the directory is different
2. Parameter file description
1. Description of settings. txt
a. By configuring settings. txt, fill in the path of source end and target end. If it ends with a backslash, it means filling in a folder, and if it doesn't end with a backslash, it means filling in a file
b. If the folder is automatically generated by date, replace it with {YYYYMMMDD} or {MMDD}, etc.
c. File support * Match any name
d. In no_create_ok_file group, ok identity is not generated, and in create_ok_file group, ok identity is generated
e. If settings. txt is not filled in correctly, running this applet will generate 1 error. log, but will not affect the subsequent copies
Example
D:\ test3\ {YYYYMMDD}\ = E:\ test4\ {YYYYMMDD}\ If you do not fill in the date when executing the program and enter directly, this {YYYYMMDD} will be automatically replaced with the date of the day, and if you fill in the date (such as 20191115), then {YYYYMMDD} will be automatically replaced with 20191115
D:\ test1\ fa* = E:\ test2\, which means copying all the files starting with fa in the D:\ test1 directory to E:\ test2
2. Description of okfile. txt
okfile. txt fills in the ok file on the source side. Some systems will generate an ok file when generating files, indicating that the system files have been generated. okfile. txt is to verify whether these files exist. If they do not exist, an warn. log will be generated when running this applet, but the actual copy will not be affected.
3. Description of procedures
Because business people don't understand python and don't install a development environment, it is convenient for them to operate by packaging python files into an exe.
pip isntall PyInstaller # Installation PyInstaller Bag
pyinstaller -F filetran.py --icon=rocket.ico # Will .py Documents and .ico Files are placed in 1 Up, in dist Generate under the directory exe Documents
Since my py file needs to read these two configuration files, I also need to put the. exe file and these two configuration files under the same directory, and then I can execute them under any one windows
Step 4 Attach code
filetran.py
# autor: yangbao
# date: 2019-10-16
import os
import time
import datetime
import re
import shutil
import configparser
def variable_replace(variable):
""" Path substitution """
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():
""" Read settings.txt File, aligning the mapping relationship between the source side and the target side """
source_to_target_dict = {}
with open('settings.txt', 'r', encoding='utf-8-sig') as f:
for line in f.readlines():
# Exclude comments and blank lines and incorrectly formatted
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):
""" Read configuration file """
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():
""" File copy """
# Get the mapping table
source_to_target_dict = source_to_target()
# Read every 1 Target paths
for ori_source, ori_target in source_to_target_dict.items():
source = variable_replace(ori_source)
target = variable_replace(ori_target)
# If the source side is filled with a folder
if source.endswith(os.sep):
if os.path.exists(source):
file_list = os.listdir(source)
for filename in file_list:
# If the destination path does not exist, create
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, ' Start copying ', 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, ' Copy complete ', sep='')
# If the source side is filled with a file
else:
source_dir = source[0:source.rfind(os.sep)+1] # Get the folder where the file is located
file_name_pattern = source[source.rfind(os.sep)+1:] # Get the file style of the file
if os.path.exists(source_dir):
file_list = os.listdir(source_dir)
for filename in file_list:
# Copy only what matches
if re.match(file_name_pattern, filename):
# If the destination path does not exist, create
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, ' Start copying ', 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, ' Copy complete ', sep='')
def warnlog():
""" Warning log """
with open('okfile.txt', 'r', encoding='utf-8') as f:
for line in f.readlines():
# Exclude comments and blank lines and incorrectly formatted
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 + ' The file does not exist! ')
t.write('\n')
if __name__ == '__main__':
# Main program
customer_input = input(' Please enter the 8 Bit specifies the date, such as 20191114 If not entered, the default copy day \n')
# If it is not entered, or the input format is correct, copy it
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'), '] ', ' File Copy Begins ...', 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'), '] ', ' End of file copy, total time spent ', cost_time, ' Seconds ', sep='')
# If the input format is incorrect
elif not re.match('\d{8}', customer_input):
print(' Please enter the correct format ')
input(' Press Enter to exit ')
settings.txt
# Copy path settings
# If the source side path does not exist, it will not be copied, and if the target side path does not exist, the directory will be automatically created
# Notes:
# 1. Format as source side path = Target path
# 2. Folder ends with a backslash \
# 3. If it is a variable, it is widened by curly braces, as it is today 20191012 , {YYYYMMDD} Will be replaced with 20191012 Use the {MMDD} Replace with 1012 , {DD} Replace with 12
# 4. YYYY MM DD Write it all in capital
# Here's an example
# Copy entire folder --> P:\ Information Technology Department \YangBao\oa\ = E:\test2\
# Copies the specified name, * Indicates matching any character --> D:\test3\{YYYYMMDD}\ab* = E:\test4\{YYYYMMDD}\
[no_create_ok_file]
# You will not need to build ok Fill in the path or file of the identification below here
D:\test3\{YYYYMMDD}\ = E:\test4\{YYYYMMDD}\
[create_ok_file]
# Will need to generate ok Fill in the path or file of the identification below here
D:\test1\ = E:\test2\
okfile.txt
# ok File Settings Settings
# Here's an example
# {YYYYMMDD} Is replaced with the specified date, D:\test3\{YYYYMMDD}\ab.txt
# D:\test3\{YYYYMMDD}\sdfg
filetran.exe
https://pan. baidu. com/s/1vxO6UycDtz5nN4DpmjLN5w Extraction code: bgdu
Note that whether you use python to execute filetran. py or click filetran. exe, you need to put it together with settings. txt and okfile. txt, otherwise the program will report an error.
The above is python to write a file distribution applet details, more information about python file distribution please pay attention to other related articles on this site!