English translation
Create a directory
AI Article Decision Snapshot
Turn the lesson into workflow, model, budget, and security checks before choosing tools.
Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.
Workflow fit
Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.
Model or tool decision
Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.
Budget and usage signal
Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.
Security and privacy review
Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.
In the previous article, we discussed the fundamentals of exception handling in Python—a cornerstone of software automation. Today, we’ll go deeper and explore how to interact with the operating system using Python, unlocking even more possibilities for automation. Understanding OS interaction not only strengthens our grasp of Python but also empowers us to perform a wide range of automated tasks.
1. What Is Operating System Interaction?
Operating system (OS) interaction refers to the exchange of information between a program and the underlying operating system. Using Python, we can leverage dedicated libraries to execute system commands, manipulate the file system, retrieve system information, and more. This capability greatly simplifies automation workflows.
2. Using the os Module
Python’s built-in os module provides a comprehensive set of functions for interacting with the operating system. In this section, we’ll cover several commonly used features.
2.1 Getting the Current Working Directory
The os.getcwd() function returns the current working directory. For example:
import os
current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")
2.2 Changing the Working Directory
To change the current working directory, use os.chdir(). For example:
import os
os.chdir('/path/to/directory') # Replace with your desired path
print(f"New working directory: {os.getcwd()}")
2.3 Listing Directory Contents
Use os.listdir() to retrieve all files and subdirectories within a specified directory:
import os
directory_contents = os.listdir('.')
print("Contents of current directory:")
for item in directory_contents:
print(item)
2.4 Creating and Removing Directories
Create directories with os.mkdir() and remove empty ones with os.rmdir(). For example:
import os
# Create a directory
try:
os.mkdir('new_folder')
print("Directory created successfully")
except Exception as e:
print(f"Error creating directory: {e}")
# Remove a directory
try:
os.rmdir('new_folder')
print("Directory removed successfully")
except Exception as e:
print(f"Error removing directory: {e}")
3. Using the subprocess Module
Beyond os, the subprocess module enables execution of system commands and bidirectional communication with them—allowing you to run any command available in your shell.
3.1 Executing Simple Commands
Use subprocess.run() to execute basic commands. For instance, list files in long format using ls -l:
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print("Command output:\n", result.stdout)
3.2 Capturing Error Output
When a command fails, its error output can be captured and inspected—for example:
import subprocess
result = subprocess.run(['non_existent_command'], capture_output=True, text=True)
if result.returncode != 0:
print("Command execution failed:")
print(result.stderr)
4. Case Study: Organizing Files Automatically
Let’s build a practical example: automating desktop file organization. This script lists files on the desktop and moves them into categorized folders based on file type.
import os
import shutil
# Get desktop path
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
os.chdir(desktop_path)
# Create category folders
folders = ['Images', 'Documents', 'Videos', 'Others']
for folder in folders:
if not os.path.exists(folder):
os.mkdir(folder)
# Move files by extension
for file in os.listdir('.'):
if os.path.isfile(file):
if file.endswith(('.png', '.jpg', '.jpeg')):
shutil.move(file, 'Images/')
elif file.endswith(('.pdf', '.docx', '.txt')):
shutil.move(file, 'Documents/')
elif file.endswith(('.mp4', '.mkv')):
shutil.move(file, 'Videos/')
else:
shutil.move(file, 'Others/')
print("File organization completed.")
5. Summary
In this article, we learned how to interact with the operating system using Python—primarily through the os and subprocess modules—to perform foundational automation tasks such as navigating directories, managing files and folders, and executing shell commands. These skills lay the groundwork for more advanced file operations.
In the next article, we’ll dive deeper into Python’s file I/O capabilities—including reading, writing, copying, and deleting files.
Mastering OS interaction makes Python significantly more versatile for automation—boosting productivity and broadening our understanding of real-world software development.
Apply This Lesson
Turn this article into AI software, model, API, and security decisions.
English Article FAQ
Use this article as evidence before choosing AI tools
How should I use this AI Tutorials article?
Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.
Is this English article different from the Chinese original?
The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.
What should I read after Create a directory?
Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.
Can this article alone choose an AI product or model?
No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.
Continue