122. Using os for OS-level Operations
Here are 10 Python code snippets demonstrating how to interact with the operating system using the functions from the os module:
1. Checking if a File or Directory Exists
import os
# Check if a file exists
file_path = 'test_file.txt'
if os.path.exists(file_path):
print(f"{file_path} exists.")
else:
print(f"{file_path} does not exist.")2. Creating a Directory
import os
# Create a directory
directory_path = 'my_folder'
if not os.path.exists(directory_path):
os.mkdir(directory_path)
print(f"Directory '{directory_path}' created.")
else:
print(f"Directory '{directory_path}' already exists.")3. Changing the Current Working Directory
4. Listing Files in a Directory
5. Removing a File
6. Removing a Directory
7. Getting Environment Variables
8. Getting File Information
9. Executing Shell Commands
10. Renaming a File
These snippets demonstrate how to use the os module to perform various operating system-level operations, including file management, directory handling, environment interaction, and executing system commands.
Last updated