首页 > 解决方案 > 如何使用python重命名同一文件夹但不同子文件夹中不同格式的文件

问题描述

我有一种情况,我必须重命名文件夹中的文件。请找到场景,

例子 :

Elements(Main Folder)<br/>
    2(subfolder-1) <br/>
       sample_2_description.txt(filename1)<br/>
       sample_2_video.avi(filename2)<br/>
    3(subfolder2)
       sample_3_tag.jpg(filename1)<br/>
       sample_3_analysis.GIF(filename2)<br/>
       sample_3_word.docx(filename3)<br/>

我想将文件的名称修改为,

Elements(Main Folder)<br/>
    2(subfolder1)<br/>
       description.txt(filename1)<br/>
       video.avi(filename2)<br/>
    3(subfolder2)
       tag.jpg(filename1)<br/>
       analysis.GIF(filename2)<br/>
       word.docx(filename3)<br/>

有人可以指导如何编写代码吗?

标签: python-3.x

解决方案


重命名文件的递归目录遍历可以基于这个答案。我们需要做的就是在接受的答案中替换文件名而不是扩展名。

这是一种方法 - 拆分文件名_并使用拆分列表的最后一个索引作为新名称


import os
import sys

directory = os.path.dirname(os.path.realpath("/path/to/parent/folder")) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
    for filename in files:
        subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
        filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
        newFilePath = filePath.split("_")[-1] #create the new name by splitting the old name by _ and grabbing last index
        os.rename(filePath, newFilePath) #rename your file

希望这可以帮助。


推荐阅读