Working With OS Module in Python:
OS module is one of the most useful modules in a Python programming language. In this post, we will learn Working With OS Module in Python. Using the OS module we can control our OS-level tasks like copy, move, format, shutdown, exit, kill, etc. So let’s see how we can work with the os module. OS module is a standard library module, so you don’t need to install anything extra.
import os
This line imports the os module, which provides functions for interacting with the operating system.
1. File and Directory Management:
Get the current directory:
import os
cwd = os.getcwd()
print("Current working directory:", cwd)
# output: /home/cybercript/Onedrive/Desktop/content-for-website
Changes the current working directory:
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
# D:\Online Class\Python For Websites
# Current working directory before
2. Creating a Directory
There are different methods available to crate the directory (folders). There are:
- os.mkdir()
- os.makedirs()
Using os.mkdir():
import os
# Creates a new directory at the specified path.
new_dir_name = "my_new_directory"
os.mkdir(new_dir_name)
Using os.makedirs():
import os
new_dir_path = "/path/to/create/new/dir"
# The exist_ok=True argument prevents errors if the directory already exists.
os.makedirs(new_dir_path, exist_ok=True)
os.listdir(path=’.’):
import os
files_and_dirs = os.listdir()
print(files_and_dirs)
os.isfile(path):
- Check if the given path is a file.
- Returns True if it’s a file, False otherwise.
import os
is_file = os.isfile("my_file.txt")
print(is_file)
os.isdir(path):
- Checks if the given path is a directory.
- Returns True if it’s a directory, False otherwise.
import os
is_dir = os.isdir("my_directory")
print(is_dir)
os.remove(path):
- Deletes a file at the specified path.
- Caution: Use with care, as deleted files are gone permanently.
import os
file_to_delete = "myfile.txt"
os.remove(file_to_delete)
os.rmdir(path):
- Deletes an empty directory at the specified path.
- Caution: Use with care, as deleted directories cannot be recovered.
import os
empty_dir = "empty_dir"
os.rmdir(empty_dir)
os.rename(old_path, new_path):
- Renames a file or directory.
import os
old_name = "old_file.txt"
new_name = "new_file.txt"
os.rename(old_name, new_name)
3. File Path Manipulation:
os.path.join(path1, path2, …):
Joins multiple path components into a single path, handling separators (slashes or backslashes) appropriately for the operating system.
import user
base_dir = "/home/user"
file_name = "data.csv"
full_path = os.path.join(base_dir, file_name)
print(full_path) # Output: /home/user/data.csv
There are a lot of features of OS modules. you don’t need to learn each and all for the beginner stage. You can learn the basics and then read the OS module documentation according to your usage. I shared what is most used in our program.
Always Remind: OS module can delete your files, can unexpectedly shut down, can format data. So, before executing any OS level program verify the program.
I hope you understand “Working With OS Module in Python”. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀