codescracker
python

Python OS Module



« Python Tutorial Python Examples »

The os module provides functions, used to interact with operating system using Python program such as creating files, deleting files, renaming files etc. This article deals with these functions of os module in Python:

Let's explain these functions briefly along with its example program, one by one.

getcwd() Function of os Module

The getcwd() function of os module, used to find the current working directory. The name getcwd stands for get current working directory. Here is an example program, uses getcwd():

import os

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

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

python os module getcwd

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

Here is the 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.

chdir() Function of os Module

The chdir() function of os module, used to change the current working directory from the program. The function chdir stands for change directory. Here is an example program of os.chdir() function:

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 same name say codescracker.txt. One inside the codescracker folder, and one outside. The inside folder should contain the text Hello. Here is the snapshot of the folder along with opened, newly created file:

python os module chdir function

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

python os module chdir example

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

import os

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

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

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

python os module change directory

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

mkdir() Function of os Module

The mkdir() function of os module, 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\codescracker). That is, using the program given below, a new directory C:\Users\DEV\codescracker\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), Other (1)) shows in above snapshot, automatically applied, after clicking on the Date modified tab to sort the files, modified by date. This is none of your interest, but I've to tell the thing 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 the snapshot of the output produced by 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

See, the folder cc is successfully created after executing the program. In above program, the statement:

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 may arise, in most of the programmer's mind, after seeing the above code is, what if the directory 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 folder to create:

python os module create directory

Note - You can create the folder inside any directory. To do this task, change the directory using os.chdir() first, then do the similar thing as done in above program.

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

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

with following block:

except FileExistsError as fee:
    print(fee)

Note - I've used as keyword to create alias fee of FileExistsError.

The output produced by above program, with same user input, will looks like:

python os module example

That is, the error says in second line is:

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

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

makedirs() Function of os Module

The function makedirs() of os module, used to create directories or multiple directory using one 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 in better way:

import os

print("Enter the Name of Folder to Create: ", end="")
folder = input()
mydir = "C:\\Users\\DEV\\codescracker\\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 same user input as done in the sample run. The directory C:\Users\DEV\codescracker\myfolder\year\2021\Sep gets created. Here is the snapshot of the newly created directory using above Python program:

python os module makedirs example

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

listdir() Function of os Module

The function listdir() of os module, used to list out all the directories from the current directory by default. To list or print all the files and folders from another directory, then use os.chdir() to change to current working directory first to that directory, of which, you want to list all the files and folders. You can try it out. But I'm going to create a program with 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 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 above program, shows all the files and folders available in the directory C:\Users\DEV

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

remove() Function of os Module

The remove() function of os module, 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 its sample run with user input codescracker.txt as name of file to delete from the current directory. Because I've not provided any directory or path, therefore by default, the file from current directory gets deleted. Here is the snapshot taken from sample run of 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, rather it is a folder ?
The solution of these two questions is to handle exceptions raised after the file is not found or if the file entered is not available, rather the folder with same name is available. The exceptions are PermissionError, when there is no file but a folder with same name, and FileNotFoundError, when file is not found. Let's first create a program that handles only 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 same user input as of previous program's sample run:

python os module remove

Since the file codescracker.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 FileNotFoundError exception. Let's create another program, that handles multiple exceptions along with printing of 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 as same file name as of previous program:

python os module remove program

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

rmdir() Function of os Module

The rmdir() function of os module, used to remove directory.

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 directory to delete from the current directory.

python os module rmdir

Now the cc directory or folder from the current directory gets deleted. Let's create another program, after modifying the above, that handles error when user enters a directory that does not exist or 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 same user input as of 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 FileNotFoundError error, basically say the directory is not available.

rename() Function of os Module

The rename() function of os module, used to rename 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 with yourfolder after executing the above program. Here is the snapshot of the directory:

python os module rename method

You can also change the name of file with the same program. Let's modify the above program, and create another one, that receives the name of file/folder from user at run time to rename. Also the program handles errors, when the file/folder does not exists:

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 same user input. Since the file myfile.txt gets renamed using above sample run, then providing the same file as old one to rename with new, the program produces or raises FileNotFoundError exception:

python os module rename example

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

path.exists() Function of os Module

The os.path.exists() function in Python, used to check whether the given path exists/available 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\codescracker:

python os module path exists

Since the os.path.exists() returns True or False. That is, True when path exists, or False when path does not exits. Therefore, I've directly placed the code as the condition of the if statement.

The path may be the directory or file.

path.getsize() Function of os Module

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


« Python Tutorial Python Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker