🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The os module in Python provides a way of using operating system-dependent functionality, such as reading or writing to the file system, handling environment variables, and interacting with the operating system.
Table of Contents
- Introduction
- Key Functions and Methods
os.nameos.getcwdos.chdiros.listdiros.mkdiros.makedirsos.removeos.rmdiros.removedirsos.renameos.statos.systemos.environos.path
- Examples
- Working with Directories
- Working with Files
- Interacting with the System
- Managing Environment Variables
- Real-World Use Case
- Conclusion
- References
Introduction
The os module is a part of the standard library and provides a way to interact with the operating system. It includes functions for file and directory manipulation, process management, and more. This makes it used for performing system-level tasks.
Key Functions and Methods
os.name
Returns the name of the operating system-dependent module imported.
import os
print(os.name) # 'posix', 'nt', 'os2', 'ce', 'java', 'riscos'
os.getcwd
Returns the current working directory.
import os
print(os.getcwd())
os.chdir
Changes the current working directory.
import os
os.chdir('/path/to/directory')
print(os.getcwd())
os.listdir
Returns a list of the entries in the specified directory.
import os
print(os.listdir('.'))
os.mkdir
Creates a directory.
import os
os.mkdir('new_directory')
os.makedirs
Creates a directory and all intermediate directories.
import os
os.makedirs('new_directory/sub_directory')
os.remove
Removes a file.
import os
os.remove('file.txt')
os.rmdir
Removes a directory.
import os
os.rmdir('directory')
os.removedirs
Removes a directory and all intermediate directories.
import os
os.removedirs('new_directory/sub_directory')
os.rename
Renames a file or directory.
import os
os.rename('old_name.txt', 'new_name.txt')
os.stat
Performs a stat system call on the given path.
import os
print(os.stat('file.txt'))
os.system
Executes a command in the system shell.
import os
os.system('ls -l')
os.environ
A dictionary representing the string environment.
import os
print(os.environ)
print(os.environ['HOME'])
os.path
The os.path module provides a way to perform operations on pathnames.
import os
print(os.path.join('dir', 'file.txt'))
print(os.path.exists('file.txt'))
print(os.path.isdir('dir'))
print(os.path.isfile('file.txt'))
Examples
Working with Directories
import os
# Get current working directory
cwd = os.getcwd()
print(f'Current working directory: {cwd}')
# Change directory
os.chdir('/path/to/directory')
print(f'Changed working directory to: {os.getcwd()}')
# List directory contents
contents = os.listdir('.')
print(f'Directory contents: {contents}')
# Create a new directory
os.mkdir('new_dir')
print('Created directory: new_dir')
# Remove a directory
os.rmdir('new_dir')
print('Removed directory: new_dir')
Working with Files
import os
# Create a new file
with open('test_file.txt', 'w') as f:
f.write('Hello, World!')
# Rename the file
os.rename('test_file.txt', 'renamed_file.txt')
print('File renamed to: renamed_file.txt')
# Remove the file
os.remove('renamed_file.txt')
print('Removed file: renamed_file.txt')
Interacting with the System
import os
# Execute a system command
os.system('echo Hello, World!')
Managing Environment Variables
import os
# Get an environment variable
home_dir = os.environ.get('HOME')
print(f'Home directory: {home_dir}')
# Set an environment variable
os.environ['MY_VARIABLE'] = 'value'
print(f'MY_VARIABLE: {os.environ["MY_VARIABLE"]}')
Real-World Use Case
Creating a Project Directory Structure
import os
def create_project_structure(base_path, project_name):
os.makedirs(os.path.join(base_path, project_name, 'src'))
os.makedirs(os.path.join(base_path, project_name, 'tests'))
os.makedirs(os.path.join(base_path, project_name, 'docs'))
print(f'Created project structure for {project_name}')
# Example usage
create_project_structure('/path/to/projects', 'my_project')
Conclusion
The os module in Python is used for interacting with the operating system. It provides a wide range of functionalities for file and directory manipulation, process management, and environment variable handling, making it essential for many system-level programming tasks.
References
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment