os.walk()

os.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Example:

Python3




# Driver function
import os
  
for (root,dirs,files) in os.walk('/home/nikhil/Desktop/', topdown=True):
    print (root)
    print (dirs)
    print (files)
    print ('--------------------------------')


Output:

10 Python File System Methods You Should Know

While programming in any language, interaction between the programs and the operating system (Windows, Linux, macOS) can become important at some point in any developer’s life. This interaction may include moving files from one location to another, creating a new file, deleting a file, etc. 

In this article, we will discuss 10 essential file system methods of the OS and Shutil module in Python that helps to interact with our operating system and use OS-dependent functionalities.

Similar Reads

os.getcwd()

os.getcwd() method tells us the location of the current working directory (CWD)....

os.chdir()

...

os.listdir()

os.chdir() method in Python used to change the current working directory to a specified path. It takes only a single argument as a new directory path....

os.walk()

...

os.path.join()

os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned....

os.makedirs()

...

shutil.copy2()

os.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames)....

shutil.move()

...

os.remove()

os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end....

shutil.rmtree()

...