The Python os
module is one of the most essential modules for interacting with the Operating System — especially for tasks like:
file creation,
file reading/writing,
directory operations,
environment variables,
path handling, etc.
os
The os
module doesn't directly create or write files (you use open()
for that), but you can use it to check existence and create empty files:
import os
file_path = "example.txt"
# Create an empty file if it doesn't exist
if not os.path.exists(file_path):
with open(file_path, 'w') as f:
pass # or f.write('') to write an empty string
open()
)os
sets the path, but actual read/write is done with open()
.
with open("example.txt", "w") as f:
f.write("Hello, world!\n")
f.write("This is a second line.\n")
with open("example.txt", "a") as f:
f.write("Appended line.\n")
with open("example.txt", "r") as f:
content = f.read()
print(content)
os.mkdir("my_folder")
os.makedirs("parent_folder/child_folder/grandchild", exist_ok=True)
if os.path.exists("my_folder"):
print("Folder exists")
os.remove("example.txt")
os.rmdir("my_folder")
Use shutil
:
import shutil
shutil.rmtree("parent_folder")
os.rename("old_name.txt", "new_name.txt")
os.rename("old_folder", "new_folder")
files = os.listdir(".") # List everything in current directory
print(files)
# List only files
only_files = [f for f in os.listdir('.') if os.path.isfile(f)]
os.path
or pathlib
)file_path = os.path.join("folder", "file.txt")
print(file_path)
# Get absolute path
abs_path = os.path.abspath(file_path)
print(abs_path)
# Get directory name
print(os.path.dirname(abs_path))
# Get file name
print(os.path.basename(abs_path))
# Check file extension
print(os.path.splitext(file_path))
# Read env variable
db_path = os.getenv("DB_PATH", "default_path.db")
# Set env variable (session-based, does not persist)
os.environ["MY_ENV"] = "value"
print(os.environ["MY_ENV"])
Task | Preferred |
---|---|
Cross-platform paths | Use os.path.join() or pathlib.Path() |
Directory creation | Use os.makedirs(..., exist_ok=True) |
Path manipulations | Use os.path or pathlib |
Deleting folders with content | Use shutil.rmtree() |
Operation | Module |
---|---|
Path building, checking, existence | os , os.path |
File read/write | open() |
File/Folder creation/removal | os , shutil |
Environment variables | os.environ , os.getenv() |