用Python替换所有子目录中文件名的一部分

问题描述 投票:0回答:1

我正在尝试用文件名的一部分替换所有子目录中文件的一部分。

我已经设法在脚本所在的当前文件夹中执行此操作,但是我需要它才能用于所有子文件夹。

这是我用来重命名当前文件夹中文件的代码:

import os
path =  os.getcwd()
filenames = os.listdir(path)

for filename in filenames:
    os.rename(filename, filename.replace("PART_TO_REPLACE", "NEW_PART"))

这是我尝试使其适用于我的文件夹中的所有子目录:

import os
path = "C:/Users/me/Desktop/Python test"

for root,dirname,filename in os.walk(path):   
     for filename in filenames:
        os.rename(filename, filename.replace("PART_TO_REPLACE", "NEW_PART"))

运行第二个脚本时没有任何反应。我的文件未重命名。我也没有收到任何错误消息。

我的Python Shell弹出窗口显示:

Python 3.8.2 (v3.8.2:7b3ab5921f, Feb 24 2020, 17:52:18) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
======= RESTART: /Users/me/Desktop/Python test/Child Rename.py =======
>>> 

谢谢

python file rename subdirectory
1个回答
0
投票

尝试一下:

for root, dirnames, filenames in os.walk(path):
    for filename in filenames:
        file = os.path.join(root, filename)
        os.rename(file, file.replace("PART_TO_REPLACE", "NEW_PART"))
© www.soinside.com 2019 - 2024. All rights reserved.