Efficiently removing subdirectories in dirnames from os.walk

后端 未结 2 1378
轮回少年
轮回少年 2021-01-12 11:52

On a mac in python 2.7 when walking through directories using os.walk my script goes through \'apps\' i.e. appname.app, since those are really just directories of themselves

2条回答
  •  半阙折子戏
    2021-01-12 12:38

    Perhaps this example from the Python docs for os.walk will be helpful. It works from the bottom up (deleting).

    # Delete everything reachable from the directory named in "top",
    # assuming there are no symbolic links.
    # CAUTION:  This is dangerous!  For example, if top == '/', it
    # could delete all your disk files.
    import os
    for root, dirs, files in os.walk(top, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    

    I am a bit confused about your goal, are you trying to remove a directory subtree and are encountering errors, or are you trying to walk a tree and just trying to list simple file names (excluding directory names)?

提交回复
热议问题