Get absolute paths of all files in a directory Get absolute paths of all files in a directory python python

Get absolute paths of all files in a directory


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

import osdef 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 osfor root, dirs, files in os.walk(os.path.abspath("../path/to/dir/")):    for file in files:        print(os.path.join(root, file))


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 pathlibfor filepath in pathlib.Path(directory).glob('**/*'):    print(filepath.absolute())