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

时间:2019-05-09 07:20:29

标签: python python-3.x text-processing python-textprocessing

我有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....

2 个答案:

答案 0 :(得分:0)

尝试:

import os
import sys

if len(sys.argv) < 2:
    sys.exit(2)

dir_name = sys.argv[1]
x = 1
files = os.listdir(dir_name)
for file in files:
    file = os.path.join(dir_name, file)
    if os.path.isfile(file):
        filename, file_extension = os.path.splitext(file)
        os.chdir(dir_name)
        new_name = 'note ' + str(x) + file_extension
        if new_name not in files:
            os.rename(file, new_name)
    x += 1

答案 1 :(得分:0)

使用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)