- Python Basics
- Python Tutorial
- Python Applications
- Python Versions
- Python environment setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control and Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break vs. continue
- Python pass vs. continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List vs. Tuple vs. Dict vs. Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date and Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes and Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class vs. Static Method
- Python @property Decorator
- Python Keywords
- Python Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
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:
- os.getcwd()
- os.chdir()
- os.mkdir()
- os.makedirs()
- os.listdir()
- os.remove()
- os.rmdir()
- os.rename()
- os.path.exists()
- os.path.getsize()
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:
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:
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:
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:
and put the text "World" in the outside file. Here is the snapshot:
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:
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:
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:
And here is the snapshot of the folder after executing the above 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:
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:
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."
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:
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:
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:
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:
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:
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.
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:
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:
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:
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:
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:
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."
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:
« Previous Tutorial Next Tutorial »