os.walk without digging into directories below

前端 未结 20 1282
庸人自扰
庸人自扰 2020-12-04 06:21

How do I limit os.walk to only return files in the directory I provide it?

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for         


        
20条回答
  •  一向
    一向 (楼主)
    2020-12-04 07:10

    Since Python 3.5 you can use os.scandir instead of os.listdir. Instead of strings you get an iterator of DirEntry objects in return. From the docs:

    Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because DirEntry objects expose this information if the operating system provides it when scanning a directory. All DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

    You can access the name of the object via DirEntry.name which is then equivalent to the output of os.listdir

提交回复
热议问题