I’m trying to make a script to list all directories, subdirectories, and files in a given directory.
I tried this:
import sys, os
root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")
for r, d, f in os.walk(path):
for file in f:
print(os.path.join(root, file))
Unfortunately, it doesn’t work properly. I get all the files, but not their complete paths.
For example, if the directory struct would be:
/home/patate/directory/targetdirectory/123/456/789/file.txt
It would print:
/home/patate/directory/targetdirectory/file.txt
I need the first result.
Use
os.path.jointo concatenate the directory and file name:Note the usage of
pathand notrootin the concatenation, since usingrootwould be incorrect.In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to
os.path.joinwould be:The advantage of
pathlibis that you can use a variety of useful methods on paths. If you use the concretePathvariant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.