简体   繁体   English

Python:递归函数中的os.walk()

[英]Python: os.walk() in recursive function

I'm trying to use os.walk() in a recursive function to go through a whole directory recursively and rename files (just capitalising names of all files at a given path) . 我试图在递归函数中使用os.walk()来递归遍历整个目录并重命名文件(只是将给定路径中所有文件的名称大写)。 My (simple) code is here: 我的(简单)代码在这里:

def recursiveRename(path):
    """ This uses the os.walk function to walk through a directory """
    rename(path)
    for root, sub, files in os.walk(path):
        i = 0
        print (sub)
        while(i < len(sub)):
            print (os.path.join(path, sub[i]))
            recursiveRename(os.path.join(path, sub[i]))
            i+=1

Which outputs this: 输出以下内容:

['one', 'two']
/Users/name/Desktop/test/one
['four', 'three']
/Users/name/Desktop/test/one/four
[]
/Users/name/Desktop/test/one/three
[]
[]
[]
/Users/name/Desktop/test/two
[]
['four', 'three']
/Users/name/Desktop/test/four

This renames all the files fine, but the last directory it tries doesn't exist (there are no subfolders in /test/two). 这样可以重命名所有文件,但是它尝试的最后一个目录不存在(/ test / two中没有子文件夹)。 I could just catch the error, but I feel my logic is a bit wrong and I'd rather figure that out. 我可以捕捉到错误,但是我觉得我的逻辑有点错误,我宁愿找出来。

os.walk() already recurses through your directories, you don't need to recurse again . os.walk() 在您的目录中递归,您无需再次递归。

Move rename(path) into your loop instead: 而是将rename(path)移动到循环中:

for root, sub, files in os.walk(path):
    rename(root)

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

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