Get absolute paths of all files in a directory

痞子三分冷 提交于 2019-12-17 21:46:43

问题


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 of directories and files, but that doesn't seem to get me what I want.


回答1:


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))



回答2:


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))



回答3:


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



回答4:


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())



回答5:


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)))



回答6:


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



回答7:


from glob import glob


def absolute_file_paths(directory):
    return glob(join(directory, "**"))



回答8:


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)



回答9:


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



回答10:


Try:

from pathlib import Path
path = 'Desktop'
files = list(filter(lambda filepath: filepath.is_file(), pathlib.Path(path).glob('*')))
for file in files:
   print(file.absolute())


来源:https://stackoverflow.com/questions/9816816/get-absolute-paths-of-all-files-in-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!