How Python interacts with your operating system and executes system-level tasks
Many automation and scripting tasks require interacting with the operating system. Python provides built‑in modules to manage files, directories, environment variables, and even run system commands.
The os module gives you access to many OS‑level operations.
import os
print(os.getcwd())
files = os.listdir(".")
print(files)
os.mkdir("new_folder")
os.rmdir("new_folder")
Use os.path to build safe, cross‑platform paths:
path = os.path.join("folder", "file.txt")
print(path)
Environment variables store configuration outside your code.
import os
api_key = os.getenv("API_KEY")
print(api_key)
Use os.system() for simple commands:
os.system("echo Hello")
subprocess is more powerful and secure than os.system().
import subprocess
result = subprocess.run(["echo", "Hello"], capture_output=True, text=True)
print(result.stdout)
subprocess.run(["python", "script.py"])
try:
subprocess.run(["ls", "nonexistent"], check=True)
except subprocess.CalledProcessError:
print("Command failed!")
Now that you can interact with the operating system, you're ready to explore how Python works with files and data formats in Lesson 25: Working with CSV and Excel Files.
← Back to Lesson Index