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

时间:2019-02-18 10:59:15

标签: python file-rename

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

让我们说包含tif文件的文件夹“ a”,“ b”和“ c”位于D:\ photos

  • D:\ photos的许多文件夹中有许多文件

那是我到目前为止的去处:

import os

os.chdir('C:/photos')

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

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

为什么不起作用?

1 个答案:

答案 0 :(得分:0)

只要您拥有Python 3.4 +,pathlib就会非常简单:

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的文件都将重命名为{{1} },第二个覆盖第一个)。