我正在尝试重命名每个通配符子文件夹中的较小文件。 文件夹路径如下所示:
C:\Users\user\Documents\Requests\*\dir\*\.txt
到目前为止,我想出了如何通过指定主文件夹和子文件夹来重命名较小的文件,但是我有太多文件夹,并且想知道是否有办法使用通配符一次重命名它们。
这是我到目前为止所做的:
import os
import glob
directory = C:\Users\user\Documents\Requests\MainFolder-timestamp\dir\Subfolder-timestamp\file-timestamp.txt
list = glob.glob(directory)
small_list = []
pairs = []
for file in list:
location = os.path.join(directory, file)
size = os.path.getsize(location)
pairs.append((size, file))
pairs.sort(key=lambda, s: s[0])
for pair in pairs:
small_list.append(pair[1]
if 'test' in small_list[-1]: # remove 'test' string from the biggest file
biggest_file = small_list[-1]
os.rename(biggest_file, biggest_file.replace('test', ''))
small_list = small_list[:-1]
for filename in small_list:
if filename.endswith('txt'):
os.rename(filename, filename[:-4] + '.txtsmall')
print('Files have been successfully renamed.')