Get absolute paths of all files in a directory

半城伤御伤魂 提交于 2019-11-28 16:49:29

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

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

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

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

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())
AmjadHD
from glob import glob


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

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