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.
Using os
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))
Files
Some of the methoods of the os module to work with files.
rename() method :
It is used to rename a file or directory.
os.rename(old_filename,new_filename)
Example
os.rename(“file.txt”, “user.txt”)
remove() method :
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”)
Directories
CWD :
CWD == "Current working directory"
getcwd() method :
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.
mkdir() method :
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.
chdir() method :
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")
rmdir() method :
It is used to delete a directory. The directory must be empty before it is deleted.
os.rmdir("dirname")
listdir() method :
Returns a list containing names of files and subdirectories in the specified directory.
print(os.listdir())
Keep Learning!!
Keep Coding....❤️👩💻
Top comments (9)
100% of these functions and the majority of this module ought to be considered deprecated by pathlib and shutil. If you are still using os for filesystem operations, you are making your life harder than it needs to be.
docs.python.org/3/library/pathlib....
docs.python.org/3/library/shutil.html
Nice, but expects more 😀
Thanks , I will try to improve next time .
Hey its just a feedback. Nothing personal.
Yes, i know but it's good to know me that where I am wrong and needs to improve....
Nicee!!
Thankyou ❤️
🤩🤩 niiiiccceee
Thankyou @tapish1511