Can I somehow save the output of os.walk()
in variables ? I tried
basepath, directories, files = os.walk(path)
but it didn't work. I want to proceed the files of the directory and one specific subdirectory. is this somehow possible ? Thanks
Asked
Active
Viewed 2,175 times
2 Answers
3
os.walk()
returns a generator that will successively return all the tree of files/directories from the initial path it started on. If you only want to process the files in a directory and one specific subdirectory you should use a mix of os.listdir()
and a mixture of os.path.isfile()
and os.path.isdir()
to get what you want.
Something like this:
def files_and_subdirectories(root_path):
files = []
directories = []
for f in os.listdir(root_path):
if os.path.isfile(f):
files.append(f)
elif os.path.isdir(f):
directories.append(f)
return directories, files
And use it like so:
directories,files = files_and_subdirectories(path)

entropy
- 3,134
- 20
- 20
-
thats a wonderful solution, i'll expand it by listing the subdirectory and i have what i want Thanks – mut3chs Mar 01 '13 at 20:06
1
I want to proceed the files of the directory and one specific subdirectory. is this somehow possible ?
If that's all you want then simply try
[e for e in os.listdir('.') if os.path.isfile(e)] + os.listdir(special_dir)

Abhijit
- 62,056
- 18
- 131
- 204