os.walk(): path, directories and files

os.walk(top, topdown=True, onerror=None, followlinks=False)
top : Root Path of the directories
topdown : 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.

Returns a Generator.

Create this directory structure or run the code below to create the same.
creating multiple directories and files using loop
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

In above code add the option 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']
---

os : operating system interfaces os.mkdir()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer