This module provides a portable way of using operating system dependent functionality.
If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module.
For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.
To work with the OS module, we need to import the OS module.
There are several functions which can be performed using Python OS module, we go through some of them here
The name of the operating system is returned by the name() function.
Currently, it registers ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.
import os print(os.name)
The os.mkdir() function is used to create new directory. Consider the following example.
import os os.mkdir("e:\\temp")
This creates a new directory to the path in the string argument of the function in the E drive named folder temp.
The getcwd() method returns the path of the current working directory
import os print(os.getcwd())
The chdir() function is used to change the current working directory. In this example we change to D
import os os.chdir("d:\\")
The remove() function deletes or removes a file from the system. We supply the name of the file and the path, and it will delete the file.
You do not need to specify the path when deleting a file from the current directory; however, we must specify the path when removing files or directories from other directories.
import os os.remove("file.txt") print("file is removed!!")
The rename() function renames a file that already exists
It takes two arguments as parameters,the first argument is the old name and the second argument is the new name of file:
import os os.rename("file1","file2")
The rmdir() function is used to remove a directory from the operating system. It removes the directory and takes the file’s name and path as arguments.
There must be no files present in the directory.
The rmdir() function cannot be used to remove the current working directory.
import os os.rmdir("d:\\testfolder")