I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I'm using Python 3.2
from os import * from os.path import * def dir_contents(path): contents = listdir(path) files = [] folders = [] for i, item in enumerate(contents): if isfile(contents[i]): files += [item] elif isdir(contents[i]): folders += [item] return files, folders
To traverse the directory in Python, use the os. walk() function. The os. walk() function accepts four arguments and returns 3-tuple, including dirpath, dirnames, and filenames.
Python method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.
Take a look at the os.walk
function which returns the path along with the directories and files it contains. That should considerably shorten your solution.
os.walk
and os.scandir
are great options, however, I've been using pathlib more and more, and with pathlib you can use the .glob()
method:
root_directory = Path(".") for path_object in root_directory.glob('**/*'): if path_object.is_file(): print(f"hi, I'm a file: {path_object}") elif path_object.is_dir(): print(f"hi, I'm a dir: {path_object}")
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