import os
import re
def rename_files(basedir, src_str, dst_str):
tuple3 = os.walk(basedir)
for path, _, files in tuple3:
for filename in files:
if not re.search(src_str, filename) is None:
old_fullname = os.path.join(path, filename)
new_filename = re.sub(src_str, dst_str, filename)
new_fullname = os.path.join(path, new_filename)
print(f'{
old_fullname} -> {
new_fullname}')
os.renames(old_fullname, new_fullname)
def recursion_rename_files(basedir, src_str, dst_str):
files = os.listdir(basedir)
for filename in files:
full_name = os.path.join(basedir, filename)
if os.path.isdir(full_name):
recursion_rename_files(full_name, src_str, dst_str)
else:
if not re.search(src_str, filename) is None:
new_filename = re.sub(del_str, dst_str, filename)
new_fullname = os.path.join(basedir, new_filename)
os.renames(full_name, new_fullname)
print(f'{
full_name} -> {
new_fullname}')
def recursion_add_zero(basedir, target_len):
files = os.listdir(basedir)
for filename in files:
old_fullname = os.path.join(basedir, filename)
if os.path.isdir(old_fullname):
recursion_add_zero(old_fullname, target_len)
else:
s = re.findall("[0-9]+", filename)
if len(s) > 0 and 0 < len(s[0]) < target_len:
zero_count = target_len - len(s[0])
new_filename = zero_count * '0' + filename
new_fullname = os.path.join(basedir, new_filename)
os.renames(old_fullname, new_fullname)
print(f'[{
old_fullname} -> {
new_fullname}] success.')
if __name__ == '__main__':
base_dir = "/Users/zjw/Desktop/test"
del_str = '[0]+'
rep_str = ''
rename_files(base_dir, del_str, rep_str)
文章评论