如何在Python中重命名文本文件



我有100个文本文件,我想在order

中重命名文件
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模块

ex:

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)

最新更新