Get absolute paths of all files in a directory

后端 未结 11 2204
一向
一向 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:19

    If you have Python 3.4 or newer you can use pathlib (or a third-party backport if you have an older Python version):

    import pathlib
    for filepath in pathlib.Path(directory).glob('**/*'):
        print(filepath.absolute())
    
    0 讨论(0)
  • 2020-12-12 19:20

    You can use os.path.abspath() to turn relative paths into absolute paths:

    file_paths = []
    
    for folder, subs, files in os.walk(rootdir):
      for filename in files:
        file_paths.append(os.path.abspath(os.path.join(folder, filename)))
    
    0 讨论(0)
  • 2020-12-12 19:24

    Try:

    from pathlib import Path
    path = 'Desktop'
    files = filter(lambda filepath: filepath.is_file(), Path(path).glob('*'))
    for file in files:
       print(file.absolute())
    
    0 讨论(0)
  • 2020-12-12 19:25

    I wanted to keep the subdirectory details and not the files and wanted only subdirs with one xml file in them. I can do it this way:

    for rootDirectory, subDirectories, files in os.walk(eventDirectory):
      for subDirectory in subDirectories:
        absSubDir = os.path.join(rootDirectory, subDirectory)
        if len(glob.glob(os.path.join(absSubDir, "*.xml"))) == 1:
          print "Parsing information in " + absSubDir
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-12 19:33

    All files and folders:

    x = [os.path.abspath(os.path.join(directory, p)) for p in os.listdir(directory)]
    

    Images (.jpg | .png):

    x = [os.path.abspath(os.path.join(directory, p)) for p in os.listdir(directory) if p.endswith(('jpg', 'png'))]
    
    0 讨论(0)
提交回复
热议问题