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
Since Python 3.4 there is new module pathlib. So to get all dirs and files one can do:
Try using the
append
method.Instead of the built-in os.walk and os.path.walk, I use something derived from this piece of code I found suggested elsewhere:
http://code.google.com/p/mylibs/source/browse/lib/Python/MyPyLib/DirectoryStatWalker.py
I won't repaste it here, but it walks the directories recursively and is quite efficient and easy to read.
If you want to recursively iterate through all the files, including all files in the subfolders, I believe this is the best way.
I've not tested this extensively yet, but I believe this will expand the
os.walk
generator, join dirnames to all the file paths, and flatten the resulting list; To give a straight up list of concrete files in your search path.