test / danbooru /rename_file.py
Oosayam's picture
Upload 180 files
8156697 verified
import os
import re
def rename_files(start_num):
# 獲取當前目錄中的所有文件
files = [f for f in os.listdir() if os.path.isfile(f)]
# 使用正則表達式匹配文件名中的數字
regex = re.compile(r'(\d+)')
files_with_numbers = [(f, regex.search(f)) for f in files]
# 過濾出包含數字的文件
files_with_numbers = [(f, match) for f, match in files_with_numbers if match]
# 按文件名中的數字排序
files_with_numbers.sort(key=lambda x: int(x[1].group()))
# 依次重新命名文件
for i, (filename, match) in enumerate(files_with_numbers):
# 新的數字
new_num = start_num + i
# 新的文件名
new_filename = regex.sub(str(new_num), filename)
# 重命名文件
os.rename(filename, new_filename)
print(f'Renamed: {filename} -> {new_filename}')
# 從用戶輸入獲取開始的數字
start_num = int(input("Enter the starting number: "))
# 執行重命名操作
rename_files(start_num)