I'm trying to make a script to list all directory, subdirectory, 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)
Unfortunatly it doesn't work properly.
I get all the files, but not their complete paths.
For example if the dir struct would be:
/home/patate/directory/targetdirectory/123/456/789/file.txt
It would print:
/home/patate/directory/targetdirectory/file.txt
What I need is the first result. Any help would be greatly appreciated! Thanks.
The dir command displays a list of files and subdirectories in a directory. With the /S option, it recurses subdirectories and lists their contents as well.
listdir() function. A simple solution to list all subdirectories in a directory is using the os. listdir() function. However, this returns the list of all files and subdirectories in the root directory.
path. join() and you will get the full path directly (if you wish), you can do this in Python 3.5 and above. Returns a list of all subfolders with their full paths. This again is faster than os.
Use os.path.join
to concatenate the directory and file name:
for path, subdirs, files in os.walk(root): for name in files: print(os.path.join(path, name))
Note the usage of path
and not root
in the concatenation, since using root
would be incorrect.
In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join
would be:
pathlib.PurePath(path, name)
The advantage of pathlib
is that you can use a variety of useful methods on paths. If you use the concrete Path
variant 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.
Just in case... Getting all files in the directory and subdirectories matching some pattern (*.py for example):
import os from fnmatch import fnmatch root = '/some/directory' pattern = "*.py" for path, subdirs, files in os.walk(root): for name in files: if fnmatch(name, pattern): print os.path.join(path, name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With