What is the Python way to walk a directory tree?

后端 未结 11 1547
走了就别回头了
走了就别回头了 2020-12-06 09:52

I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I\'m using Python 3.2

from os import *
from os.pat         


        
11条回答
  •  有刺的猬
    2020-12-06 09:56

    Indeed using

    items += [item]
    

    is bad for many reasons...

    1. The append method has been made exactly for that (appending one element to the end of a list)

    2. You are creating a temporary list of one element just to throw it away. While raw speed should not your first concern when using Python (otherwise you're using the wrong language) still wasting speed for no reason doesn't seem the right thing.

    3. You are using a little asymmetry of the Python language... for list objects writing a += b is not the same as writing a = a + b because the former modifies the object in place, while the second instead allocates a new list and this can have a different semantic if the object a is also reachable using other ways. In your specific code this doesn't seem the case but it could become a problem later when someone else (or yourself in a few years, that is the same) will have to modify the code. Python even has a method extend with a less subtle syntax that is specifically made to handle the case in which you want to modify in place a list object by adding at the end the elements of another list.

    Also as other have noted seems that your code is trying to do what os.walk already does...

提交回复
热议问题