Get absolute paths of all files in a directory

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

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

Solution 3:

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

Solution 4:

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