Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

10 Python File System Methods You Should Know

  • Last Updated : 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()

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

Example:

Python3




# Python program to explain os.getcwd() method
          
# importing os module
import 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()

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 library
import os
  
# change the current directory
# to specified directory
os.chdir(r"C:\Users\Gfg\Desktop\geeks")
  
print("Directory changed")

Output:

Directory changed

os.listdir()

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 module
import os
  
# Get the path of current working directory
path = '/home'
  
# Get the list of all files and directories
# in current working directory
dir_list = os.listdir(path)
  
print("Files and directories in '", path, "' :")
print(dir_list)

Output:

Files and directories in ' /home ' :
['nikhil']

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:

python os.walk

os.path.join()

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 module
import os
  
# Path
path = "/home"
  
# Join various path components
print(os.path.join(path, "User/Desktop", "file.txt"))
  
  
# Path
path = "User/Documents"
  
# Join various path components
print(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.
  
  
# Path
path = "/home"
  
# Join various path components
print(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
Output
/home/User/Desktop/file.txt
/home/file.txt
/home/User/Public/Documents/

os.makedirs()

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 module
import os
   
# Leaf directory
directory = "nikhil"
   
# Parent Directories
parent_dir = "/home/User/Documents/GeeksForGeeks/Authors"
   
# Path
path = os.path.join(parent_dir, directory)
   
# Create the directory
# 'ihritik'
os.makedirs(path)
print("Directory '%s' created" %directory)

Output:

Directory 'nikhil' created

shutil.copy2()

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

shutil.copy2

Python3




# Python program to explain shutil.copy2() method
  
# importing os module
import os
  
# importing shutil module
import shutil
  
# path
path = '/home/nikhil/Desktop/new'
  
# List files and directories
# in '/home/User/Documents'
print("Before copying file:")
print(os.listdir(path))
  
  
# Source path
source = "/home/nikhil/Desktop/new/pdf.py"
  
# Print the metadeta
# of source file
metadata = os.stat(source)
print("Metadata:", metadata, "\n")
  
# Destination path
destination = "/home/nikhil/Desktop/new/copy_pdf.py"
  
# Copy the content of
# source to destination
dest = 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 file
matadata = os.stat(destination)
print("Metadata:", metadata)
  
# Print path of newly
# created file
print("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.copy2

shutil.move()

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

shutil.move

Python3




# Python program to explain shutil.move() method
      
# importing os module
import os
  
# importing shutil module
import shutil
  
# path
path = '/home/nikhil/Desktop/'
  
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before moving file:")
print(os.listdir(path))
  
  
# Source path
source = '/home/nikhil/Desktop/new'
  
# Destination path
destination = '/home/nikhil/Desktop/new2'
  
# Move the content of
# source to destination
dest = 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 file
print("Destination path:", dest)

Output:

shutil.moveshutil.move

os.remove()

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 module
import os
  
# File name
file = 'file.txt'
  
# File location
location = "/home/User/Documents"
  
# Path
path = 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()

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:

shutil.rmtree()

# Directory inside parent directory:

shutil.rmtree()

# File inside the sub-directory:

python shutil.rmtree()

Python3




# Python program to demonstrate
# shutil.rmtree()
  
import shutil
import os
  
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
  
# directory
dir = "Authors"
  
# path
path = os.path.join(location, dir)
  
# removing directory
shutil.rmtree(path)

Output:

python shutil.rmtree()

Refer to the below articles for our complete tutorial on the OS module and Shutil module.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!