OS Module In Python
The os module in Python is a built-in library that provides functions for interacting with the operating system. It allows you to perform a wide variety of tasks, such as reading and writing files, interacting with the file system, and running system commands.
Here are some common tasks you can perform with the os module:
- Creating a new directory:
os.mkdir("my_directory") - Checking if a file exists:
os.path.exists("file.txt") - Listing the contents of a directory:
os.listdir("my_directory") - Changing the current working directory:
os.chdir("new_directory") - Renaming a file:
os.rename("old_file.txt", "new_file.txt") - Accessing environment variables:
os.environ["HOME"](for example, to get the home directory path)
Reading and writing files :The os module provides functions for opening, reading, and writing files. For example, to open a file for reading, you can use the open function:
import os
# Open the file in read-only mode
f = os.open("myfile.txt", os.O_RDONLY)
# Read the contents of the file
contents = os.read(f, 1024)
# Close the file
Get Shivam Shukla’s stories in your inbox
Join Medium for free to get updates from this writer.
To open a file for writing, you can use the os.O_WRONLY flag:
import os
# Open the file in write-only mode
f = os.open("myfile.txt", os.O_WRONLY)
# Write to the file
os.write(f, b"Hello, world!")
# Close the file
os.close(f)Interacting with the file system
The os module also provides functions for interacting with the file system. For example, you can use the os.listdir function to get a list of the files in a directory:
import os
# Get a list of the files in the current directory
files = os.listdir(".")
print(files) You can also use the os.mkdir function to create a new directory:
import os
# Create a new directory
os.mkdir("newdir")Running system commands
Finally, the os module provides functions for running system commands. For example, you can use the os.system function to run a command and get the output:
import os
# Run the "ls" command and print the output
output = os.system("ls")
print(output) You can also use the os.popen function to run a command and get the output as a file-like object:
import os
# Run the "ls" command and get the output as a file-like object
f = os.popen("ls")
# Read the contents of the output
output = f.read()
print(output)
# Close the file-like object
f.close()In simple terms, the os module gives you the tools to interact with the files and directories on your computer, navigate the file system, and access system-related information. It's a handy module for building programs that need to work with files, directories, and system configuration.







