10 Python File System Methods You Should Know - GeeksforGeeks

19 Oct, 2021
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.
os.getcwd() method tells us the location of the current working directory (CWD).
Example:
Python3
# Python program to explain os.getcwd() method          # importing os moduleimport os      # Get the current working# directory (CWD)cwd = os.getcwd()      # Print the current working# directory (CWD)print("Current working directory:", cwd)
Output:
Current working directory: /home/nikhil/Desktop/gfg
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.
Python3
# Python3 program to change the# directory of file using os.chdir() method  # import os libraryimport os  # change the current directory# to specified directoryos.chdir(r"C:\Users\Gfg\Desktop\geeks")  print("Directory changed")
Output:
Directory changed
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.
Example:
Python3
# Python program to explain os.listdir() method      # importing os moduleimport os  # Get the path of current working directorypath = '/home'  # Get the list of all files and directories# in current working directorydir_list = os.listdir(path)  print("Files and directories in '", path, "' :")print(dir_list)
Output:
Files and directories in ' /home ' :
['nikhil']
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 functionimport os  for (root,dirs,files) in os.walk('/home/nikhil/Desktop/', topdown=True):    print (root)    print (dirs)    print (files)    print ('--------------------------------')
Output:
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. 
Python3
# Python program to explain os.path.join() method  # importing os moduleimport os  # Pathpath = "/home"  # Join various path componentsprint(os.path.join(path, "User/Desktop", "file.txt"))    # Pathpath = "User/Documents"  # Join various path componentsprint(os.path.join(path, "/home", "file.txt"))  # In above example '/home'# represents an absolute path# so all previous components i.e User / Documents# are thrown away and joining continues# from the absolute path component i.e / home.    # Pathpath = "/home"  # Join various path componentsprint(os.path.join(path, "User/Public/", "Documents", ""))  # In above example the last# path component is empty# so a directory separator ('/')# will be put at the end# along with the concatenated value
/home/User/Desktop/file.txt
/home/file.txt
/home/User/Public/Documents/
os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all. For example consider the following path:
/home/User/Documents/GeeksForGeeks/Authors/nikhil
Suppose we want to create a directory ‘nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘nikhil’ directory will be created. 
Example:
Python3
# Python program to explain os.makedirs() method     # importing os moduleimport os   # Leaf directorydirectory = "nikhil"   # Parent Directoriesparent_dir = "/home/User/Documents/GeeksForGeeks/Authors"   # Pathpath = os.path.join(parent_dir, directory)   # Create the directory# 'ihritik'os.makedirs(path)print("Directory '%s' created" %directory)
Output:
Directory 'nikhil' created
shutil.copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method but it also tries to preserve the file’s metadata.
Example:
Directory Used
Python3
# Python program to explain shutil.copy2() method  # importing os moduleimport os  # importing shutil moduleimport shutil  # pathpath = '/home/nikhil/Desktop/new'  # List files and directories# in '/home/User/Documents'print("Before copying file:")print(os.listdir(path))    # Source pathsource = "/home/nikhil/Desktop/new/pdf.py"  # Print the metadeta# of source filemetadata = os.stat(source)print("Metadata:", metadata, "\n")  # Destination pathdestination = "/home/nikhil/Desktop/new/copy_pdf.py"  # Copy the content of# source to destinationdest = shutil.copy2(source, destination)  # List files and directories# in "/home / User / Documents"print("After copying file:")print(os.listdir(path))  # Print the metadata# of the destination filematadata = os.stat(destination)print("Metadata:", metadata)  # Print path of newly# created fileprint("Destination path:", dest)
Output:
Before copying file:
[‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
After copying file:
[‘copy_pdf.py’, ‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
Destination path: /home/nikhil/Desktop/new/copy_pdf.py
Directory
shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.rename() semantics.
Example:
Directory Used
Python3
# Python program to explain shutil.move() method      # importing os moduleimport os  # importing shutil moduleimport shutil  # pathpath = '/home/nikhil/Desktop/'  # List files and directories# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'print("Before moving file:")print(os.listdir(path))    # Source pathsource = '/home/nikhil/Desktop/new'  # Destination pathdestination = '/home/nikhil/Desktop/new2'  # Move the content of# source to destinationdest = shutil.move(source, destination)  # List files and directories# in "C:/Users / Rajnish / Desktop / GeeksforGeeks"print("After moving file:")print(os.listdir(path))  # Print path of newly# created fileprint("Destination path:", dest)
Output:
os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. 
Example:
Python3
# Python program to explain os.remove() method      # importing os moduleimport os  # File namefile = 'file.txt'  # File locationlocation = "/home/User/Documents"  # Pathpath = os.path.join(location, file)  # Remove the file# 'file.txt'os.remove(path)print("%s has been removed successfully" %file)
Output:
file.txt has been removed successfully
shutil.rmtree() is used to delete an entire directory tree, path must point to a directory.
Example: Suppose the directory and sub-directories are as follow.
# Parent directory:
# Directory inside parent directory:
# File inside the sub-directory:
Python3
# Python program to demonstrate# shutil.rmtree()  import shutilimport os  # locationlocation = "D:/Pycharm projects/GeeksforGeeks/"  # directorydir = "Authors"  # pathpath = os.path.join(location, dir)  # removing directoryshutil.rmtree(path)
Output:
Refer to the below articles for our complete tutorial on the OS module and Shutil module.
OS Module in Python with Examples
Shutil Module in Python
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python