In python, the file system contains the files and directories. To handle these files and directories python supports “os” module. Python has the “os” module, which provides us with many useful methods to work with directories (and files as well).
The os module provides us the methods that are involved in file processing operations and directory processing like renaming, deleting, get current directory, changing directory etc.
The os module provides us the rename() method which is used to rename the specified file to a new name.
Syntax:os.rename (“current-name”, “new-name”)
import os;
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")
The os module provides us the remove() method which is used to remove the specified file.
Syntax:os.remove(“file-name”)
import os;
#deleting the file named file3.txt
os.remove("file3.txt")
The mkdir() method is used to create the directories in the current working directory.
Syntax:os.mkdir(“directory-name”)
import os;
#creating a new directory with the name new
os.mkdir("dirnew")
The chdir() method is used to change the current working directory to a specified directory.
Syntax:os.chdir("new-directory")
import os;
#changing the current working directory to new
os.chdir("dir2")
This method returns the current working directory.
Syntax:os.getcwd()
import os;
#printing the current working directory
print(os.getcwd())
The rmdir() method is used to delete the specified directory.
Syntax:os.rmdir(“directory name”)
import os;
#removing the new directory
os.rmdir("dir2")
All files and sub directories inside a directory can be known using the listdir() method. This method takes in a path and returns a list of sub directories and files in that path. If no path is specified, it returns from the current working directory.
Syntax:os.listdir([“path”])
import os;
#list of files and directories in current working directory
print(os.listdir())
#list of files and directories in specified path
print(os.listdir(“D:\\”))