Skip to content
Advertisement

How can I retun a list of absolute paths?

The following code returns a list of file-names in a given directory:

def get_files(dir_path_str):
    onlyfiles = next(os.walk(dir_path_str))[2]
    return onlyfiles

How can I make it return absolute file paths with minimal modification and preserve the behavior of the function?

Advertisement

Answer

The easiest way to do this is with pathlib

Make your input directory a Path object, use .iterdir() to get all the files/folders inside that directory, use .absolute() to make them absolute and .is_file() to check that they’re files:

from pathlib import Path


def get_files(inp_path_str):
    directory = Path(inp_path_str)
    only_files = [file.absolute() for file in directory.iterdir() if file.is_file()]
    return only_files

If you want the paths to be strings rather than Path objects, pathlib Paths can have str() called on them:

only_files = [str(file.absolute()) for file in directory.iterdir() if file.is_file()]

Or as a fully expanded loop rather than a list comprehension:

def get_files(inp_path_str):
    directory = Path(inp_path_str)
    only_files = []
    for file in directory.iterdir():
        if file.is_file():
            only_files.append(str(file.absolute()))
    return only_files
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement