os.walk(top, topdown=True, onerror=None, followlinks=False)
top : Root Path of the directoriestopdown : True ( default ), the triple for a directory is generated before the triples for any of its subdirectories onerror : errors are ignored ( by default ) , or a callback function with one argument can be used.followlinks : False ( default) Set value to True to visit directories pointed to by symlinks, on systems that support them.
import os
drive='D:\\'
sub_path='my_dir\\'
os.mkdir(drive+sub_path) # create directory D:\my_dir
for i in range(3): # update the level required.
sub_path=sub_path+'my_dir'+str(i)+'\\'
path=drive + sub_path
print(path)
os.mkdir(path)
path_file=path+'my_file'+str(i)+'.txt'
print(path_file)
f = open(path_file, "w")
Let us check the returned data type. (code with output )
import os
path='D:\\my_dir\\my_dir0'
t=os.walk(path)
print(type(t)) # <class 'generator'>
We will get the path , directory and files. (code with outputs)
import os
path='D:\\my_dir\\my_dir0'
root=next(os.walk(path))[0]
dirnames=next(os.walk(path))[1]
files=next(os.walk(path))[2]
print(root) # D:\my_dir\my_dir0
print(dirnames) # ['my_dir1']
print(files) # ['my_file0.txt']
Using for loop we can display the path , directories and files inside different sub directories.
import os
path='D:\\my_dir\\my_dir0'
for root, dirnames, filenames in os.walk(path):
print(root)
print(dirnames)
print(filenames)
print('---')
Output is here
D:\my_dir\my_dir0
['my_dir1']
['my_file0.txt']
---
D:\my_dir\my_dir0\my_dir1
['my_dir2']
['my_file1.txt']
---
D:\my_dir\my_dir0\my_dir1\my_dir2
[]
['my_file2.txt']
---
topdown=False. Changes in for loop code is here.
for root, dirnames, filenames in os.walk(path,topdown=False):
Check this output ( compare with previous output )
D:\my_dir\my_dir0\my_dir1\my_dir2
[]
['my_file2.txt']
---
D:\my_dir\my_dir0\my_dir1
['my_dir2']
['my_file1.txt']
---
D:\my_dir\my_dir0
['my_dir1']
['my_file0.txt']
---
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.