还是为了那个该死的流程文档,每个月枯燥而乏味的报工需要填一堆的模板文档,为了节省时间只能自己想办法,用python 3来实现批量修改创建目录文件的功能。
所谓会者不难难者不会,一个批量创建目录和创建测试空文件的功能居然折腾了快三天的时间,还写的有点混乱,不过总算是成功了,根据给定的基础目录,在该目录下创建子目录,并且在子目录下边再创建四个不同类型的office文档,到这算是成功了一半。
本次卡住时间最长的应该算是修改文件名中部分内容,而且因为每个子目录中所要修改的文件名内容也需要单独指定,所以就要一层又一层的嵌套循环,不知道效率如何但写成这样估计快不了,起码功能实现了,代码贴上以备不时之需。
# -*-encoding:utf-8-*-
import os
import re
gname = {}
chage = ""
file_extention = ""
def createFile(fpath, dname=None, fname=None, keys=None):
filename = ""
if dname is None:
dname = []
if fname is None:
fname = []
root_path = fpath
for d in list(dname):
abs_path = os.path.join(root_path, d)
os.chdir(abs_path)
for f in range(0, len(fname)):
file_name = os.path.splitext(fname[f])[0]
end_name = os.path.splitext(fname[f])[-1]
# print(os.path.join(abs_path,fname[f]))
with open(fname[f], "w", encoding="utf-8"):
pass
def createDir(fpath, *fname):
dir_list = list(fname)[0]
try:
for dir_name in dir_list:
os.makedirs(os.path.join(fpath, dir_name), exist_ok=False)
# print(os.path.join(fpath, dir_name))
except FileExistsError as e:
print(e)
exit(300)
if os.path.isdir(fpath):
file_path = fpath
for root, dirs, files in os.walk(file_path):
print(root)
def changeChar(matched):
temp_char = matched.groups()
return temp_char[0] + "_" + temp_char[1] + "_" + temp_char[2] + "_" + chage + file_extention
def renameTaskFile(fpath, chars):
root_path = fpath
char_dict = chars
pattern_dir = r"R2102[0-9]*$"
pattern_file = r"(\S[^_]*)_(\S[^_]*)_(\S[^_]*)_(\S[^_]*)"
for root, dirs, files in os.walk(fpath):
dir_ma = re.search(pattern_dir, root)
if dir_ma:
print(root)
for k, v in char_dict.items():
if k == dir_ma.group(0):
global chage
chage = v
# return chage
for i in files:
global file_extention
file_extention = os.path.splitext(i)[-1]
ma = re.sub(pattern_file, changeChar, i)
old_file_name = os.path.join(root, i)
new_file_name = os.path.join(root, ma)
print(old_file_name)
os.renames(old_file_name, new_file_name)
print(new_file_name)
if __name__ == '__main__':
bfpath = r"F:\PycharmProjects\learnprocess01\testmain"
fpath = r"D:\PycharmProjects\firstpythonproject\renames_test"
dname = ["R21021209", "R21021210", "R21021211", "R21021212"]
key_char = ["测试---1", "测试---2", "测试---3", "测试---4"]
gname = dict(zip(dname, key_char))
print(gname)
filenames = ["SMDB_服务器信息管理系统_程序修改清单_应急场景开发-物理服务器故障场景.doc",
"SMDB_服务器信息管理系统_代码走查单_应急场景开发-物理服务器故障场景.xls",
"SMDB_服务器信息管理系统_功能点估计_应急场景开发-物理服务器故障场景.doc",
"SMDB_服务器信息管理系统_技术测试报告_应急场景开发-物理服务器故障场景.doc"]
# createFile(fpath, dname, filenames, key_char)
#
# createDir(fpath, dname)
renameTaskFile(fpath, gname)
# for root, dirs, files in os.walk(fpath):
# print(files)下一步就是要引入可以编辑doc和xls文档的模块,来批量修改文件中的内容,当然内容也会不同文件各自有不同的修改,估计又会是一个更多的套娃循环,先到这吧,碎觉。
查看更多关于Python 3 实现创建目录文件及修改文件名的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did163496