如何重命名 python 中的文本文件?

How to rename text files in python?

我有 100 个文本文件,我想按顺序重命名文件

my text files looks like this 

note 1.txt, note 6.txt,note 15.txt,note 24.txt
i need to be renamed as note 1.txt,note 2.txt,note 3.txt,.....
i'm facing an issue like this 

Cannot create a file when that file already exists: 'note 1.txt' -> 'note 6.txt'

it should come in order  of 1,2,3....

使用 osre 模块

例如:

import os
import re
path = "Your Path"

for num, file in enumerate(sorted(os.listdir(path), key=lambda x: int(re.search(r"(\d+)", x).group(1))), 1):
    if not re.search(r"\b{}\.txt".format(num), file):
        print("Rename", file, num)
        os.rename(os.path.join(path, file), os.path.join(path, re.sub(r"\d+", str(num), file)))
    else:
        print("Good", file, num)