Get absolute paths of all files in a directory

后端 未结 11 2240
一向
一向 2020-12-12 19:00

How do I get the absolute paths of all the files in a directory that could have many sub-folders in Python?

I know os.walk() recursively gives me a list

11条回答
  •  既然无缘
    2020-12-12 19:28

    Starting with python 3.5 the idiomatic solution would be:

    import os
    
    def absolute_file_paths(directory):
        path = os.path.abspath(directory)
        return [entry.path for entry in os.scandir(path) if entry.is_file()]
    

    This not just reads nicer but also is faster in many cases. For more details (like ignoring symlinks) see original python docs: https://docs.python.org/3/library/os.html#os.scandir

提交回复
热议问题