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
Copy
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
Copy
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
Copy
4. Listing Files in a Directory
Copy
5. Removing a File
Copy
6. Removing a Directory
Copy
7. Getting Environment Variables
Copy
8. Getting File Information
Copy
9. Executing Shell Commands
Copy
10. Renaming a File
Copy
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