用索引重命名文件名

2024-09-29 21:56:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想重命名文件夹中的所有文件。每个文件名将从“whateverName.whateverExt到“namepre+i.whateverExt”。e、 g.从“xxxxx.jpg公司至“namepre1.jpg”

我尝试从(Rename files in sub directories)修改代码,但是失败了。。。你知道吗

import os

target_dir = "/Users/usename/dirctectory/"

for path, dirs, files in os.walk(target_dir):
    for i in range(len(files)):
        filename, ext = os.path.splitext(files[i])
        newname_pre = 'newname_pre'
        new_file = newname_pre + str(i) + ext

        old_filepath = os.path.join(path, file)
        new_filepath = os.path.join(path, new_file)
        os.rename(old_filepath, new_filepath)

有人能帮我吗? 谢谢!!!你知道吗


Tags: pathintargetnewforosdirfiles
3条回答

尝试此版本:

import os

target_dir = "/Users/usename/dirctectory/"

for path, dirs, files in os.walk(target_dir):
    for i in range(len(files)):
        filename, ext = os.path.splitext(files[i])
        newname_pre = 'newname_pre'
        new_file = newname_pre + str(i) + ext

        old_filepath = os.path.join(path, files[i]) # here was the problem
        new_filepath = os.path.join(path, new_file)
        os.rename(old_filepath, new_filepath)

可能您在命名某些变量时犯了一些错误,请尝试以下操作:

import os

target_dir = "/Users/usename/dirctectory/"
newname_tmpl = 'newname_pre{0}{1}'

for path, dirs, files in os.walk(target_dir):
    for i, file in enumerate(files):
        filename, ext = os.path.splitext(file)
        new_file = newname_tmpl.format(i, ext)
        old_filepath = os.path.join(path, file)
        new_filepath = os.path.join(path, new_file)
        os.rename(old_filepath, new_filepath)

您可能应该更新这个问题,说明当您运行这个时得到了什么输出。另外,试着在每次迭代中打印出new_file的值,看看是否得到了正确的文件路径。我猜是这样的:

new_file = newname_pre + str(i) + ext

…应该这样说:

new_file = newname_pre + str(i) + '.' + ext

…或者,用一种更为通俗的语法:

new_file = "%s%i.%s" % (newname_pre, i, ext)

相关问题 更多 >

    热门问题