Wednesday, April 8, 2020

Python - Get relative filenames recursively

I was working on a script where I needed to get all of the filenames in a directory and sub-directories, and it was a lot more convenient to use relative paths.  I didn't find exactly that via Google (or DuckDuckGo), but this works:

dir_files = []
for root, dirs, filenames in os.walk("target"):
    for filename in filenames:
        path = os.path.join(root, filename)
        rel_path = os.path.relpath(path, "target")
        dir_files.append(rel_path)
This gets all of the filenames relative to "target" - so if we are in /something/, the file "/something/target/my_directory/my_file" will be listed as  "my_directory/my_file".

Of course, this can be done with list comprehensions as well but I left it in loop form because I think that's more readable.

No comments:

Post a Comment