如何用python重命名多个文件夹中的多个文件?

2024-04-19 05:36:34 发布

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

我正在尝试删除所有索引(字符),除了最后4个索引和python中的文件扩展名。例如: a2b-0001.tif至0001.tif a3tcd-0002.tif至0002.tif as54d-0003.tif至0003.tif

假设包含这些tifs文件的文件夹“a”、“b”和“c”位于D:\photos中

  • 在D:\照片的许多文件夹中有许多这样的文件

到目前为止我就是从这里得到的:

import os

os.chdir('C:/photos')

for dirpath, dirnames, filenames in os.walk('C:/photos'):

os.rename (filenames, filenames[-8:])

为什么这样不行?你知道吗


Tags: 文件import文件夹foros字符照片filenames
1条回答
网友
1楼 · 发布于 2024-04-19 05:36:34

只要您有python3.4+,^{}就非常简单:

import pathlib

def rename_files(path):
    ## Iterate through children of the given path
    for child in path.iterdir():
        ## If the child is a file
        if child.is_file():
            ## .stem is the filename (minus the extension)
            ## .suffix is the extension
            name,ext = child.stem, child.suffix
            ## Rename file by taking only the last 4 digits of the name
            child.rename(name[-4:]+ext)

directory = pathlib.Path(r"C:\photos").resolve()
## Iterate through your initial folder
for child in directory.iterdir():
    ## If the child is a folder
    if child.is_dir():
        ## Rename all files within that folder
        rename_files(child)

请注意,由于您正在截断文件名,因此可能会发生冲突,从而导致文件被覆盖(即,12345.jpg22345.jpg文件都将重命名为2345.jpg,第二个文件将覆盖第一个文件)。你知道吗

相关问题 更多 >