Python OS Module

The OS module provides methods used to interact with the operating system using a Python program, such as creating files, deleting files, renaming files, etc. This article describes these methods of the "os" module in Python:

Let's explain these methods briefly, along with their example programs, one by one.

The os.getcwd() method

The getcwd() method of the OS module is used to find the current working directory. The name "getcwd" stands for "get current working directory." Here is an example program that uses getcwd():

import os

print("The Current Directory is:", os.getcwd())

The output produced by the above program is shown in the snapshot given below:

python os module getcwd

Note: The current directory is the path to that folder, where your Python program's source code is getting saved.

Here is a snapshot of the folder where the above program is saved:

python os module getcwd example

See the path and the source code's file, indicated using arrows.

The os.chdir() method

The os module's chdir() method is used to change the program's current working directory. The method chdir stands for "change directory." Here is an example program for the os.chdir() method:

import os

print("The Current Directory is:", os.getcwd())

os.chdir("../")
print("The Current Directory is:", os.getcwd())

Here is its sample output:

python os chdir module

Now let's create two files with the same name, say "fresherearth.txt," one inside the "fresherearth" folder and one outside. The inside of the folder should contain the text "Hello." Here is a snapshot of the folder along with the opened, newly created file:

python os module chdir function

and put the text "World" in the outside file. Here is the snapshot:

python os module chdir example

Now let's create the program, which uses chdir() of the OS module:

import os

print("The Current Directory is:", os.getcwd())
print("The file \"fresherearth.txt\" inside this directory contains:")
f = open("fresherearth.txt", "r")
print(f.read())
f.close()

os.chdir("../")
print("\nThe Current Directory is:", os.getcwd())
print("The file \"fresherearth.txt\" inside this directory contains:")
f = open("fresherearth.txt", "r")
print(f.read())
f.close()

The output produced by the above program is shown in the snapshot given below:

python os module change directory

See how the program accessed the file "fresherearth.txt," available in two different directories. You can also access any number of files using a single Python program. But before accessing the file, which is not available in the current directory, first change the directory to the desired one, then proceed. Do same before accessing any file available in any directory.

The os.mkdir() method

The mkdir() method of the OS module is used to create a new directory. The name "mkdir" stands for make directory. Therefore, I'm going to create a folder named "cc" inside the current directory ("C:\Users\DEV\fresherearth"). That is, using the program given below, a new directory, "C:\Users\DEV\fresherearth\cc" gets created. But before creating and executing the program, let's first see the snapshot of the current directory:

Python os module mkdir

Note: The numbering (A-H (2), Q-Z (1), and Other (1)) shown in the above snapshot was automatically applied after clicking on the Date modified tab to sort the files by modified date. This is none of your interest, but I've got to tell you the truth to avoid any misunderstanding.

Now let's create the program. Here is the program:

import os

folder = "cc"
cwd = os.getcwd()
path = cwd + '\\' + folder
os.mkdir(path)
print("The directory '%s' is created." %path)

Here is a snapshot of the output produced by the above program:

python os module mkdir example

And here is the snapshot of the folder after executing the above program:

python os module mkdir program

As you can see, the folder "cc" is successfully created after executing the program. In the above program, the statement is:

print("The directory '%s' is created." %path)

can also be written as:

print("The directory '", path, "' is created.", sep="")

or

print("The directory '" + path + "' is created.")

Now the question that may arise in most programmers' minds after seeing the above code is, "What if the directory is already available?"
The answer to this question is the program given below, created after modifying the above program:

import os

print("Enter the Name of Folder to Create: ", end="")
folder = input()
cwd = os.getcwd()
path = cwd + '\\' + folder
try:
    os.mkdir(path)
    print("\nThe directory '%s' is created." %path)
except FileExistsError:
    print("\nThe directory '%s' is already available." %path)

Here is its sample run with user input "cc" as the folder to create:

python os module create directory

Note: You can create the folder in any directory. To accomplish this task, first change the directory with os.chdir(), then proceed as in the preceding program.

If you want to see the actual error raised by the "FileExistsError" exception, then replace the "except" block available in the above program with:

except FileExistsError:
    print("\nThe directory '%s' is already available." %path)

with following block:

except FileExistsError as fee:
    print(fee)

Note : I've used the "as" keyword to create the alias "fee" of "FileExistsError."

The output produced by the above program, with the same user input, will look like this:

python os module example

That is, there is an error in the second line saying this:

[WinError 183] Cannot create a file when that file already exists: 'C:\Users\DEV\fresherearth\cc'

Note: To learn in detail about the end= and sep= parameters of print(), refer to its separate tutorial.

The os.makedirs() method

The method makedirs() of the OS module is used to create directories or multiple directories using a single statement.

To create a particular folder inside another particular folder or any specified directory, use os.makedirs() to do this task at one execution of the program. Let's take a look at the program given below to understand it better:

import os

print("Enter the Name of Folder to Create: ", end="")
folder = input()
mydir = "C:\\Users\\DEV\\fresherearth\\myfolder\\year\\2021"
path = mydir + '\\' + folder
try:
    os.makedirs(path)
    print("\nThe directory is created.")
except FileExistsError:
    print("The given directory is already available.")

Here is its sample run with user input "Sep."

python os module makedirs

After execution of the above program with the same user input as in the sample run, the directory "C:\Users\DEV\fresherearth\myfolder\year\2021\Sep" is created. Here is a snapshot of the newly created directory using the above Python program:

python os module makedirs example

As you can see, there are four directories: "myfolder," "year," "2021," and "Sep." But these four directories are not created separately in a single directory. Rather, "Sep" is inside "2021," "2021" is inside "year," "year" is inside "myfolder," and "myfolder" is in the current directory.

The os.listdir() method

The OS module's listdir() method is used by default to list all directories in the current directory. To list or print all the files and folders from another directory, first use os.chdir() to change the current working directory to that directory, from which you want to list all the files and folders. You can try it out. But I'm going to create a program with a default one:

import os

print("All files and directories available in current directory:")
print(os.listdir())

Here is its sample output:

python os module listdir

If you want to list out files and directories from any specified directory, then use the following program: This is the modified version of the previous program:

import os

mydir = "C:\\Users\\DEV"
files_folders = os.listdir(mydir)

print("Files and Directories in \"", mydir, "\":", sep="")
print(files_folders)

The output produced by the above program shows all the files and folders available in the directory "C:UsersDEV."

Note: It is not limited to listing files and directories from the "C" drive only. You can also list out all the files and folders or directories on any drive.

The os.remove() method

The remove() method of the os module is used to delete any file using the Python program.

import os

print("Enter the Name of File: ", end="")
file = input()
os.remove(file)
print("\nThe file \"", file, "\" deleted.", sep="")

Here is a sample run with the user-supplied filename fresherearth.txt as the name to delete from the current directory. Because I've not provided any directory or path, by default, the file in the current directory gets deleted. Here is the snapshot taken from the sample run of the above program:

python os module remove function

Now the question is, what if the given filename is not available in the directory?
Or what if the given filename is not a file but rather a folder?
The solution to these two questions is to handle exceptions raised after the file is not found or if the file entered is not available, but rather the folder with the same name is available. The exceptions are PermissionError, when there is no file but a folder with the same name, and FileNotFoundError, when a file is not found. Let's first create a program that handles only the FileNotFoundError error:

import os

print("Enter the Name of File: ", end="")
file = input()
try:
    os.remove(file)
    print("\nThe file \"", file, "\" deleted.", sep="")
except FileNotFoundError:
    print("\nThe file \"", file, "\", not found.", sep="")

Here is its sample run with the same user input as the previous program's sample run:

python os module remove

since the file fresherearth.txt is deleted using the previous program's sample run. Therefore, in this sample run, we've seen the above output. You can also produce the default error message raised by the FileNotFoundError exception. Let's create another program that handles multiple exceptions and prints the default error message.

import os

print("Enter the Name of File: ", end="")
file = input()
try:
    os.remove(file)
    print("\nThe file \"", file, "\" deleted.", sep="")
except FileNotFoundError as fnfe:
    print(fnfe)
except PermissionError as pe:
    print(pe)
except OSError as ose:
    print(ose)

Here is its sample run with user input and the same file name as the previous program:

python os module remove program

Note: To delete files from another directory, change the current working directory using os.chdir(), then process the similar program to do the task.

The os.rmdir() method

To remove directories, use the OS module's rmdir() method.

import os

print("Enter the Name of Directory: ", end="")
directory = input()
os.rmdir(directory)
print("\nThe directory \"", directory, "\" deleted.", sep="")

Here is its sample run with user input: "cc" as the name of the directory to delete from the current directory.

python os module rmdir

Now the "cc" directory or folder in the current directory gets deleted. Let's create another program, after modifying the above, that handles errors when the user enters a directory that does not exist or was not found:

import os

print("Enter the Name of Directory: ", end="")
directory = input()
try:
    os.rmdir(directory)
    print("\nThe directory \"", directory, "\" deleted.", sep="")
except FileNotFoundError as fnfe:
    print(fnfe)
except OSError as ose:
    print(ose)

Here is its sample run with the same user input as the previous program:

python os module rmdir function

Since the message is "[WinError 2] The system cannot find the file specified: 'cc'", means that the program raised the FileNotFoundError error, which basically says the directory is not available.

The os.rename() method

The rename() method of the OS module is used to rename a file or folder using the program.

import os

old_name = "myfolder"
new_name = "yourfolder"
os.rename(old_name, new_name)
print("The folder named \"", old_name, "\", renamed with \"", new_name, "\"", sep="")

Here is its sample run:

python os module rename

If you see the current directory, then the folder "myfolder" gets renamed to "yourfolder" after executing the above program. Here is a snapshot of the directory:

python os module rename method

You can also change the name of the file with the same program. Let's extend the previous program by writing another that receives the name of a file or folder from the user at run time and renames it. Also, the program handles errors when the file or folder does not exist:

import os

print("Enter the Name of Old File/Folder: ", end="")
old = input()
print("Enter the Name of New File/Folder: ", end="")
new = input()

try:
    os.rename(old, new)
    print("\nRenamed successfully!")
except FileNotFoundError as fnfe:
    print(fnfe)
except IsADirectoryError as iade:
    print(iade)
except NotADirectoryError as nade:
    print(nade)
except PermissionError as pe:
    print(pe)
except IOError as ioe:
    print(ioe)

Here is its sample run with user input, myfile.txt:

python os module rename function

And here is another sample run with the same user input. Since the file myfile.txt gets renamed using the above sample run, then providing the same file as the old one to rename with the new, the program produces or raises the FileNotFoundError exception:

python os module rename example

Note: To change the name of a file or folder from any other directory, first change the current working directory using os.chdir(), then proceed.

The os.path.exists() method

The os.path.exists() method in Python is used to check whether the given path exists or not.

import os

print("Enter the Full Path: ", end="")
path = input()
if os.path.exists(path):
    print("\nAvailable.")
else:
    print("\nNot available.")

Here is its sample run with user input "C:\Users\DEV\fresherearth."

python os module path exists

since os.path.exists() returns True or False. That is, true when a path exists and false when it does not.Therefore, I've directly placed the code as the condition of the  if statement.

The os.path.getsize() method

The os.path.getsize() method in Python is used to find the size of a directory. The size will be in bytes.

import os

print("Enter the Full Path: ", end="")
path = input()
try:
    size = os.path.getsize(path)
    print("\nSize =", size, "bytes")
except OSError as ose:
    print(ose)

Here is its sample run with user input:

python os module path getsize

Python Online Test


« Previous Tutorial Next Tutorial »