OS Module in Python with Examples - GeeksforGeeks (2024)

The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.

The *os* and *os.path* modules include many functions to interact with the file system.

Python-OS-ModuleFunctions

Here we will discuss some important functions of the Python os module :

  • Handling the Current Working Directory
  • Creating a Directory
  • Listing out Files and Directories with Python
  • Deleting Directory or Files using Python

Handling the Current Working Directory

Consider Current Working Directory(CWD) as a folder, where Python is operating. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that name-only reference will be successful only if the file is in the Python’s CWD.

Note: The folder where the Python script is running is known as the Current Directory. This is not the path where the Python script is located.

Getting the Current working directory

To get the location of the current working directory os.getcwd() is used.

Example: This code uses the os' module to get and print the current working directory (CWD) of the Python script. It retrieves the CWD using the os.getcwd()' and then prints it to the console.

Python
import os cwd = os.getcwd() print("Current working directory:", cwd) 

Output:

Current working directory: /home/nikhil/Desktop/gfg

Changing the Current working directory

To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.

Note: The current working directory is the folder in which the Python script is operating.

Example: The code checks and displays the current working directory (CWD) twice: before and after changing the directory up one level using os.chdir('../'). It provides a simple example of how to work with the current working directory in Python.

Python
import os def current_path(): print("Current working directory before") print(os.getcwd()) print() current_path() os.chdir('../') current_path() 

Output:

Current working directory before
C:\Users\Nikhil Aggarwal\Desktop\gfg
Current working directory after
C:\Users\Nikhil Aggarwal\Desktop

Creating a Directory

There are different methods available in the OS module for creating a directory. These are –

  • os.mkdir()
  • os.makedirs()

Using os.mkdir()

By using os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raises FileExistsError if the directory to be created already exists.

Example: This code creates two directories: “GeeksforGeeks” within the “D:/Pycharm projects/” directory and “Geeks” within the “D:/Pycharm projects” directory.

  • The first directory is created using the os.mkdir() method without specifying the mode.
  • The second directory is created using the same method, but a specific mode (0o666) is provided, which grants read and write permissions.
  • The code then prints messages to indicate that the directories have been created.
Python
import osdirectory = "GeeksforGeeks"parent_dir = "D:/Pycharm projects/"path = os.path.join(parent_dir, directory)os.mkdir(path)print("Directory '% s' created" % directory)directory = "Geeks"parent_dir = "D:/Pycharm projects"mode = 0o666path = os.path.join(parent_dir, directory)os.mkdir(path, mode)print("Directory '% s' created" % directory)

Output:

Directory 'GeeksforGeeks' created
Directory 'Geeks' created

Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.

Example:This code creates two directories, “Nikhil” and “c”, within different parent directories. It uses the os.makedirs function to ensure that parent directories are created if they don’t exist.

It also sets the permissions for the “c” directory. The code prints messages to confirm the creation of these directories

Python
import osdirectory = "Nikhil"parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"path = os.path.join(parent_dir, directory)os.makedirs(path)print("Directory '% s' created" % directory)directory = "c"parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"mode = 0o666path = os.path.join(parent_dir, directory)os.makedirs(path, mode)print("Directory '% s' created" % directory)

Output:

Directory 'Nikhil' created
Directory 'c' created

Listing out Files and Directories with Python

There is os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then the list of files and directories in the current working directory will be returned.

Example: This code lists all the files and directories in the root directory (“/”). It uses the os.listdir function to get the list of files and directories in the specified path and then prints the results.

Python
import os path = "/"dir_list = os.listdir(path) print("Files and directories in '", path, "' :") print(dir_list) 

Output:

Files and directories in ' / ' :
['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr',
'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']

Deleting Directory or Files using Python

OS module provides different methods for removing directories and files in Python. These are –

  • Using os.remove()
  • Using os.rmdir()

Using os.remove() Method

os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.

Example: Suppose the file contained in the folder are:

OS Module in Python with Examples - GeeksforGeeks (1)

This code removes a file named “file1.txt” from the specified location “D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/”. It uses the os.remove function to delete the file at the specified path.

Python
import os file = 'file1.txt'location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"path = os.path.join(location, file) os.remove(path) 

Output:

OS Module in Python with Examples - GeeksforGeeks (2)


Using os.rmdir()

os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

Example: Suppose the directories are

OS Module in Python with Examples - GeeksforGeeks (3)

This code attempts to remove a directory named “Geeks” located at “D:/Pycharm projects/”.

It uses the os.rmdir function to delete the directory. If the directory is empty, it will be removed. If it contains files or subdirectories, you may encounter an error.

Python
import os directory = "Geeks"parent = "D:/Pycharm projects/"path = os.path.join(parent, directory) os.rmdir(path) 

Output:

OS Module in Python with Examples - GeeksforGeeks (4)

Commonly Used Functions

Using os.name function

This function gives the name of the operating system dependent module imported. The following names have currently been registered: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.

Python
import osprint(os.name)

Output:

posix

Note: It may give different output on different interpreters, such as ‘posix’ when you run the code here.

Using os.error Function

All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.error is an alias for built-in OSError exception.

This code reads the contents of a file named ‘GFG.txt’. It uses a try…except block to handle potential errors, particularly the ‘IOError that may occur if there’s a problem reading the file.

If an error occurs, it will print a message saying, “Problem reading: GFG.txt.”

Python
import ostry: filename = 'GFG.txt' f = open(filename, 'rU') text = f.read() f.close()except IOError: print('Problem reading: ' + filename)

Output:

Problem reading: GFG.txt

Using os.popen() Function

This method opens a pipe to or from command. The return value can be read or written depending on whether the mode is ‘r’ or ‘w’.
Syntax:

 os.popen(command[, mode[, bufsize]])

Parameters mode & bufsize are not necessary parameters, if not provided, default ‘r’ is taken for mode.

This code opens a file named ‘GFG.txt’ in write mode, writes “Hello” to it, and then reads and prints its contents. The use of os.popen is not recommended, and standard file operations are used for these tasks.

Python
import osfd = "GFG.txt"file = open(fd, 'w')file.write("Hello")file.close()file = open(fd, 'r')text = file.read()print(text)file = os.popen(fd, 'w')file.write("Hello")

Output:

Hello

Note: Output for popen() will not be shown, there would be direct changes into the file.

Using os.close() Function

Close file descriptor fd. A file opened using open(), can be closed by close()only. But file opened through os.popen(), can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw TypeError.

Python
import osfd = "GFG.txt"file = open(fd, 'r')text = file.read()print(text)os.close(file)

Output:

Traceback (most recent call last):
File "C:\Users\GFG\Desktop\GeeksForGeeksOSFile.py", line 6, in
os.close(file)
TypeError: an integer is required (got type _io.TextIOWrapper)

Note: The same error may not be thrown, due to the non-existent file or permission privilege.

Using os.rename() Function

A file old.txt can be renamed to new.txt, using the function os.rename(). The name of the file changes only if, the file exists and the user has sufficient privilege permission to change the file.

Python
import osfd = "GFG.txt"os.rename(fd,'New.txt')os.rename(fd,'New.txt')

Output:

Traceback (most recent call last):
File "C:\Users\GFG\Desktop\ModuleOS\GeeksForGeeksOSFile.py", line 3, in
os.rename(fd,'New.txt')
FileNotFoundError: [WinError 2] The system cannot find the
file specified: 'GFG.txt' -> 'New.txt'

A file name “GFG.txt” exists, thus when os.rename() is used the first time, the file gets renamed.

Upon calling the function os.rename() second time, file “New.txt” exists and not “GFG.txt” thus Python throws FileNotFoundError.

Using os.remove() Function

Using the Os module we can remove a file in our system using the os.remove() method. To remove a file we need to pass the name of the file as a parameter.

Python
import os #importing os module.os.remove("file_name.txt") #removing the file.

The OS module provides us a layer of abstraction between us and the operating system.

When we are working with os module always specify the absolute path depending upon the operating system the code can run on any os but we need to change the path exactly. If you try to remove a file that does not exist you will get FileNotFoundError.

Using os.path.exists() Function

This method will check whether a file exists or not by passing the name of the file as a parameter. OS module has a sub-module named PATH by using which we can perform many more functions.

Python
import os #importing os moduleresult = os.path.exists("file_name") #giving the name of the file as a parameter.print(result)

Output:

False

As in the above code, the file does not exist it will give output False. If the file exists it will give us output True.

Using os.path.getsize() Function

In os.path.getsize() function, python will give us the size of the file in bytes. To use this method we need to pass the name of the file as a parameter.

Python
import os #importing os modulesize = os.path.getsize("filename")print("Size of the file is", size," bytes.")

Output:

Size of the file is 192 bytes.

OS Module in Python with Examples – FAQs

What is the OS module in Python?

The os module in Python provides a way to interact with the operating system. It includes functions to handle file operations, directory management, and other OS-related tasks.

import os

# Get current working directory
current_directory = os.getcwd()
print(current_directory)

# List files and directories in the current directory
files = os.listdir('.')
print(files)

What is an OS package?

An OS package generally refers to a collection of modules and tools designed to provide a standardized way of interacting with the operating system. In the context of Python, the os package/module provides functionality to interact with the operating system, allowing for file and directory manipulation, environment variable access, and process management.

What is OS name in Python?

os.name is an attribute of the os module that provides the name of the operating system-dependent module imported. This can help in identifying the platform the code is running on.

import os

# Get the OS name
os_name = os.name
print(os_name) # Output: 'posix', 'nt', 'java', etc.

What is the OS process in Python?

The OS process in Python refers to functions in the os module that allow interaction with system processes. This includes functions to create, terminate, and manage processes. For example, os.system() can be used to run shell commands.

import os

# Execute a system command
os.system('echo Hello, World!')

What is Python IO module?

The io module in Python provides the main facilities for dealing with various types of I/O (Input/Output). It is used to handle file reading and writing operations, among other I/O-related tasks. This module defines the base classes and functions for handling binary and text I/O.


Elevate your coding journey with a Premium subscription. Benefit from ad-free learning, unlimited article summaries, an AI bot, access to 35+ courses, and more-available only with GeeksforGeeks Premium! Explore now!


P

Piyush Doorwar

Improve

Previous Article

OS Module in Python with Examples

Next Article

Generating Random id's using UUID in Python

Please Login to comment...

OS Module in Python with Examples - GeeksforGeeks (2024)

FAQs

What is the os module in Python? ›

The OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules. This module provides a portable way of using operating system-dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system.

What is the advantage of os module in Python? ›

The os module in Python provides a way to interact with the operating system. It allows you to perform various operating system-related tasks such as file and directory operations, process management, environment variables manipulation, and more.

What is the difference between SYS module and os module in Python? ›

The Sys Module can access the command line arguments and the os module can access the location of the script as shown in the below code.

What is the difference between os path and os module? ›

Answer: - The os. path modules in Python contains some useful functions that are in strings or bytes which are used for different purposes like merging or retrieving the path names in the Python. While the os module in the Python provides us with some functions which are used for interacting with the operating system.

How to create files using os module in Python? ›

Using the os Module to Create Files

mknod() function to create a new file. If the file already exists, Python will raise a FileExistsError , which we catch and handle by printing an error message. This method can be useful if you want to ensure that you don't accidentally overwrite an existing file.

What is a module in Python with an example? ›

Any Python file can be referenced as a module. A file containing Python code, for example: test.py , is called a module, and its name would be test . There are various methods of writing modules, but the simplest way is to create a file with a . py extension, which contains functions and variables.

Which OS is better for Python? ›

It depends totally on your preference. In Windows, it is sometimes tricky to use python, but you can build very good GUI-based interfaces with it. However, if you are comfortable with a command-line interface then LINUX is the best OS for you to use.

How does OS system work in Python? ›

The os. system() method in Python is used for the execution of shell commands directly from a Python script. It takes command as a parameter which specifies the shell command to be executed. The command does not return the command output but instead provides an exit code indicating the command's status.

What is the difference between Pathlib and OS module in Python? ›

Python Os Module. This module provides a portable way of using operating system dependent functionality. The pathlib module provides a lot more functionality than the ones listed here, like getting file name, getting file extension, reading/writing a file without manually opening it, etc.

What is the purpose of the SYS module? ›

The python sys module provides functions and variables which are used to manipulate different parts of the Python Runtime Environment. It lets us access system-specific parameters and functions. First, we have to import the sys module in our program before running any functions.

What is the purpose of sys OS getopt module in Python? ›

This module helps scripts to parse the command line arguments in sys. argv . It supports the same conventions as the Unix getopt() function (including the special meanings of arguments of the form ' - ' and ' -- ').

What is the difference between running as script and module? ›

01:58 So, long story short: scripts are intended to be run directly, whereas modules are meant to be imported. Scripts often contain statements outside of the scope of any class or function, whereas modules define classes, functions, variables, and other members for use in scripts that import it.

What is the purpose of the OS module? ›

The OS module in Python is an indispensable tool for handling file-related tasks for programmers. The Python OS module is essential for file-related tasks, enabling efficient file and directory management in programs.

What does the OS module function remove? ›

Definition and Usage

The os. remove() method is used to delete a file path. This method can not delete a directory and if directory is found it will raise an OSError .

What does OS stand for as in the OS module )? ›

An operating system (OS) is the program that, after being initially loaded into the computer by a boot program, manages all of the other application programs in a computer. The application programs make use of the operating system by making requests for services through a defined application program interface (API).

What does os system do Python? ›

Definition and Usage

The os. system() method executes the command (a string) in a subshell. If command generates any output, it is sent to the interpreter standard output stream. The command executed on the respective shell opened by the Operating system.

What is an os package? ›

Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error.

What does os module walk do in Python? ›

Pythonos.

walk() method generates the file and directory names in a directory tree by walking the tree using top-down or bottom-up approach.

How to use os commands in Python? ›

Shell Commands with Python using OS Module

Second, in the Python file, import the os module, which contains the system function that executes shell commands. system() function takes an only string as an argument. Type whatever you want to see as an output or perform an action. Run this .

References

Top Articles
Hernán Drago, la historia del hombre detrás del modelo
How to get a Razor Claw in Pokémon Scarlet and Violet
Ron Martin Realty Cam
Odawa Hypixel
Phcs Medishare Provider Portal
Vaya Timeclock
DL1678 (DAL1678) Delta Historial y rastreo de vuelos - FlightAware
Craigslist Nj North Cars By Owner
30% OFF Jellycat Promo Code - September 2024 (*NEW*)
Corpse Bride Soap2Day
Oriellys St James Mn
Ssefth1203
De Leerling Watch Online
Methodist Laborworkx
Superhot Unblocked Games
United Dual Complete Providers
2024 U-Haul ® Truck Rental Review
Erskine Plus Portal
Seattle Rpz
Dc Gas Login
The Superhuman Guide to Twitter Advanced Search: 23 Hidden Ways to Use Advanced Search for Marketing and Sales
Dark Chocolate Cherry Vegan Cinnamon Rolls
NBA 2k23 MyTEAM guide: Every Trophy Case Agenda for all 30 teams
Odfl4Us Driver Login
Accuweather Mold Count
What Is Vioc On Credit Card Statement
PowerXL Smokeless Grill- Elektrische Grill - Rookloos & geurloos grillplezier - met... | bol
Atdhe Net
Dragger Games For The Brain
Miltank Gamepress
Talk To Me Showtimes Near Marcus Valley Grand Cinema
Greyson Alexander Thorn
Impact-Messung für bessere Ergebnisse « impact investing magazin
Roanoke Skipthegames Com
27 Modern Dining Room Ideas You'll Want to Try ASAP
Schooology Fcps
Ups Drop Off Newton Ks
Gina's Pizza Port Charlotte Fl
2487872771
Rocketpult Infinite Fuel
Metro 72 Hour Extension 2022
Whitehall Preparatory And Fitness Academy Calendar
Carteret County Busted Paper
Shoecarnival Com Careers
Goats For Sale On Craigslist
Arch Aplin Iii Felony
Booknet.com Contract Marriage 2
Understanding & Applying Carroll's Pyramid of Corporate Social Responsibility
Sam's Club Fountain Valley Gas Prices
Rise Meadville Reviews
Swissport Timecard
Wayward Carbuncle Location
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 5441

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.