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.
os.getcwd()
os.getcwd() method tells us the location of the current working directory (CWD).
Example:
Python3
import os
cwd = os.getcwd()
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
import os
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
import os
path = '/home'
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
import os
for (root,dirs,files) in os.walk( '/home/nikhil/Desktop/' , topdown = True ):
print (root)
print (dirs)
print (files)
print ( '--------------------------------' )
|
Output:
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
import os
path = "/home"
print (os.path.join(path, "User/Desktop" , "file.txt" ))
path = "User/Documents"
print (os.path.join(path, "/home" , "file.txt" ))
path = "/home"
print (os.path.join(path, "User/Public/" , "Documents" , ""))
|
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
import os
directory = "nikhil"
parent_dir = "/home/User/Documents/GeeksForGeeks/Authors"
path = os.path.join(parent_dir, directory)
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
Python3
import os
import shutil
path = '/home/nikhil/Desktop/new'
print ( "Before copying file:" )
print (os.listdir(path))
source = "/home/nikhil/Desktop/new/pdf.py"
metadata = os.stat(source)
print ( "Metadata:" , metadata, "\n" )
destination = "/home/nikhil/Desktop/new/copy_pdf.py"
dest = shutil.copy2(source, destination)
print ( "After copying file:" )
print (os.listdir(path))
matadata = os.stat(destination)
print ( "Metadata:" , metadata)
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.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
Python3
import os
import shutil
path = '/home/nikhil/Desktop/'
print ( "Before moving file:" )
print (os.listdir(path))
source = '/home/nikhil/Desktop/new'
destination = '/home/nikhil/Desktop/new2'
dest = shutil.move(source, destination)
print ( "After moving file:" )
print (os.listdir(path))
print ( "Destination path:" , dest)
|
Output:
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
import os
file = 'file.txt'
location = "/home/User/Documents"
path = os.path.join(location, file )
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:
# Directory inside parent directory:
# File inside the sub-directory:
Python3
import shutil
import os
location = "D:/Pycharm projects/GeeksforGeeks/"
dir = "Authors"
path = os.path.join(location, dir )
shutil.rmtree(path)
|
Output:
Refer to the below articles for our complete tutorial on the OS module and Shutil module.
Last Updated :
19 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...