Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python重命名多个文件夹中的多个文件?_Python_File Rename - Fatal编程技术网

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

如何使用python重命名多个文件夹中的多个文件?,python,file-rename,Python,File Rename,我正在尝试删除除最后4个索引和python中文件扩展名以外的所有索引(字符)。例如: a2b-0001.tif至0001.tif a3tcd-0002.tif至0002.tif as54d-0003.tif至0003.tif 假设包含这些tifs文件的文件夹“a”、“b”和“c”位于D:\photos中 在D:\photos中的许多文件夹中都有这些文件 到目前为止,我就是从这里得到的: import os os.chdir('C:/photos') for dirpath, dirnam

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

假设包含这些tifs文件的文件夹“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:])

为什么不起作用?

只要您有Python 3.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.jpg
22345.jpg
的文件都将重命名为
2345.jpg
,第二个文件将覆盖第一个文件).

到目前为止你都试了些什么?我刚刚补充了一个问题:你试了些什么。。对不起,我真的不擅长这个