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 existsfile_path ='test_file.txt'if os.path.exists(file_path):print(f"{file_path} exists.")else:print(f"{file_path} does not exist.")
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.
import os
# Change the current working directory
new_directory = '/home/user/Documents'
os.chdir(new_directory)
print(f"Current working directory is now: {os.getcwd()}")
import os
# List all files in a directory
directory_path = '.'
files = os.listdir(directory_path)
print(f"Files in {directory_path}: {files}")
import os
# Remove a file
file_path = 'test_file.txt'
if os.path.exists(file_path):
os.remove(file_path)
print(f"File {file_path} removed.")
else:
print(f"File {file_path} does not exist.")
import os
# Remove a directory
directory_path = 'my_folder'
if os.path.exists(directory_path):
os.rmdir(directory_path)
print(f"Directory {directory_path} removed.")
else:
print(f"Directory {directory_path} does not exist.")
import os
# Get an environment variable
user_home = os.getenv('HOME')
print(f"User's home directory: {user_home}")
import os
# Get file information
file_path = 'test_file.txt'
if os.path.exists(file_path):
file_info = os.stat(file_path)
print(f"File size: {file_info.st_size} bytes")
print(f"File created: {file_info.st_ctime}")
else:
print(f"File {file_path} does not exist.")
import os
# Run a shell command
command = 'ls -l'
result = os.system(command)
print(f"Command executed with exit code: {result}")
import os
# Rename a file
old_name = 'old_file.txt'
new_name = 'new_file.txt'
if os.path.exists(old_name):
os.rename(old_name, new_name)
print(f"Renamed {old_name} to {new_name}.")
else:
print(f"{old_name} does not exist.")