精简后的脚本:
import os
path = r'W:\xxx\xxxx'
pre_name = '20220224'
file_list = os.listdir(path)
count = 1
with open(os.path.join(path, 'save_name.txt'), "a+", encoding="utf-8" as f:
for file in file_list:
olddir = os.path.join(path, file) # 原来的文件路径
filename = os.path.splitext(file)[0] # 文件名
filetype = os.path.splitext(file) # 文件扩展名
str_name = "{}{:03}{}.format(pre_name, count, filetype)
newdir = os.path.join(path, str_name) # 新的文件路径
os.rename(olddir, newdir) # 重命名
count += 1
f.writelines("\""+file+"\"" + ' ' + "\"" + str_name + "\"" + '\n')
原来的:
from genericpath import exists
import os
# 当前工作路径
dir = os.getcwd()
# 改变到指定路径
dir = os.chdir(r'./fire')
path = '/data1/zcz/PythonRequest/fire'
file_list = os.listdir(path)
count = 1
if os.path.exists('../save_name.txt'):
with open('../save_name.txt', mode='r', encoding='utf-8') as file:
print(file.readlines())
f = open('../save_name.txt','a')
else:
with open("../save_name.txt", mode='w', encoding='utf-8') as file:
print("文件创建成功")
f = open('../save_name.txt','a')
for file in file_list:
f.write(file + '\t\t')
olddir=os.path.join(path, file) # 原来的文件路径
filename=os.path.splitext(file)[0] # 文件名
filetype=os.path.splitext(file)[1] # 文件扩展名
str_name = "20220223_" + str(count) + filetype
newdir=os.path.join(path, str_name) # 新的文件路径
os.rename(olddir, newdir) # 重命名
count += 1
f.write(str_name + '\n')