简体   繁体   English

Python 3 os.rename 将重命名文件,但不重命名文件夹

[英]Python 3 os.rename will rename files, but not folders

I am trying to rename all files and folders in a directory to replace '#' with '_'.我正在尝试重命名目录中的所有文件和文件夹以将“#”替换为“_”。 I wrote a quick Python 3.7 function to do this, and it successfully renamed all the files, but failed to rename any folder.我写了一个快速的 Python 3.7 function 来做到这一点,它成功地重命名了所有文件,但未能重命名任何文件夹。 I am not getting any errors when I run this code.运行此代码时,我没有收到任何错误。

import os

def replace(folder_path, old, new):
    for path, subdirs, files in os.walk(folder_path):
        for name in files:
            if(old in name):
                file_path = os.path.join(path,name)
                print(file_path)
                new_path = os.path.join(path,name.replace(old,new))
                print(new_path)
                os.rename(file_path, new_path)


old = '#'
new = '_'
path = 'Y:\my_path_goes_here'

replace (path, old, new)

Thanks in advance for the help.在此先感谢您的帮助。

You are iterating only over the files, subdirs contains the list of folders.遍历文件, subdirs包含文件夹列表。 More info: https://docs.python.org/3/library/os.html#os.walk更多信息: https://docs.python.org/3/library/os.html#os.walk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM