Python Menu

File System in Python


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.

Renaming the file - rename()

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”)

Example:
import os;  
#rename file2.txt to file3.txt  
os.rename("file2.txt","file3.txt")

Removing the file – remove()

The os module provides us the remove() method which is used to remove the specified file.

Syntax:
os.remove(“file-name”)

Example:
import os;  
#deleting the file named file3.txt   
os.remove("file3.txt")

Creating the new directory – mkdir()

The mkdir() method is used to create the directories in the current working directory.

Syntax:
os.mkdir(“directory-name”)

Example:
import os;  
#creating a new directory with the name new  
os.mkdir("dirnew") 

Changing the current working directory – chdir()

The chdir() method is used to change the current working directory to a specified directory.

Syntax:
os.chdir("new-directory")

Example:
import os;  
#changing the current working directory to new   
os.chdir("dir2")

Get current working directory – getpwd()

This method returns the current working directory.

Syntax:
os.getcwd()

Example:
import os;  
#printing the current working directory   
print(os.getcwd())

Deleting directory - rmdir()

The rmdir() method is used to delete the specified directory.

Syntax:
os.rmdir(“directory name”)

Example:
import os;  
#removing the new directory   
os.rmdir("dir2")

List Directories and Files – listdir()

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”])

Example:
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:\\”))

Next Topic :Exception in Python