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:

JavaScript

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:

JavaScript

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement