Get absolute paths of all files in a directory

后端 未结 11 2205
一向
一向 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:34
    from glob import glob
    
    
    def absolute_file_paths(directory):
        return glob(join(directory, "**"))
    
    0 讨论(0)
  • 2020-12-12 19:35

    os.path.abspath makes sure a path is absolute. Use the following helper function:

    import os
    
    def absoluteFilePaths(directory):
       for dirpath,_,filenames in os.walk(directory):
           for f in filenames:
               yield os.path.abspath(os.path.join(dirpath, f))
    
    0 讨论(0)
  • 2020-12-12 19:38
    for root, directories, filenames in os.walk(directory):
     for directory in directories:
             print os.path.join(root, directory)
     for filename in filenames:
         if filename.endswith(".JPG"):
            print filename
            print os.path.join(root,filename)
    
    0 讨论(0)
  • 2020-12-12 19:40

    If the argument given to os.walk is absolute, then the root dir names yielded during iteration will also be absolute. So, you only need to join them with the filenames:

    import os
    
    for root, dirs, files in os.walk(os.path.abspath("../path/to/dir/")):
        for file in files:
            print(os.path.join(root, file))
    
    0 讨论(0)
  • 2020-12-12 19:41

    Try:

    import os
    
    for root, dirs, files in os.walk('.'):
        for file in files:
            p=os.path.join(root,file)
            print p
            print os.path.abspath(p)
            print
    
    0 讨论(0)
提交回复
热议问题