24
Python : OS Module
The os module is a part of the standard library, or stdlib, within Python 3.
Python os module provides methods that help us to perform file processing operations. Let’s explore these basic functions one by one.
Before you use the os module, you first need to bring it up by means of the Python import command:
import os
If you try to run os without importing it, you will see an error message:
NameError: name 'os' is not defined
To get a list of functions supported by os module, run the below command:
print(dir(os))
Some of the methoods of the os module to work with files.
It is used to rename a file or directory.
os.rename(old_filename,new_filename)
Example
os.rename(“file.txt”, “user.txt”)
It is used to delete the file.
Path : This is a path-like object which represents a file system path. This path-like object is either a string or bytes object.
os.remove(path_of_file)
Example
os.remove(“d1/user.txt”)
CWD == "Current working directory"
returns current directory.
or
To check the path of the current working directory, we will use the getcwd method.
print(os.getcwd())
Note The folder where the Python script is running is known as the Current Directory. This is not the path where the Python script is located.
It is used to create a directory in current directory.
os.mkdir("d1")
This method raises FileExistsError if the directory to be created already exists.
Suppose, we have a folder, for example, info, inside our current directory, we can switch to the info folder, using the chdir function. or It is used to change the current directory.
os.chdir("info")
It is used to delete a directory. The directory must be empty before it is deleted.
os.rmdir("dirname")
Returns a list containing names of files and subdirectories in the specified directory.
print(os.listdir())
Keep Learning!!
Keep Coding....❤️👩💻
24