Editing File Contents
Basic File Editing Techniques
Reading File Contents
## Reading entire file
with open('example.txt', 'r') as file:
content = file.read()
## Reading line by line
with open('example.txt', 'r') as file:
lines = file.readlines()
Modification Strategies
graph TD
A[File Modification] --> B[In-Memory Editing]
A --> C[Direct File Replacement]
A --> D[Temporary File Method]
In-Memory Editing Approach
def modify_file_content(filename, old_text, new_text):
## Read the entire file
with open(filename, 'r') as file:
content = file.read()
## Replace content
modified_content = content.replace(old_text, new_text)
## Write back to file
with open(filename, 'w') as file:
file.write(modified_content)
Advanced Editing Techniques
Text Replacement Methods
Method |
Description |
Use Case |
replace() |
Simple text substitution |
Small files |
regex |
Complex pattern matching |
Advanced replacements |
fileinput |
Line-by-line editing |
Large files |
Regular Expression Editing
import re
def regex_file_edit(filename, pattern, replacement):
with open(filename, 'r') as file:
content = file.read()
modified_content = re.sub(pattern, replacement, content)
with open(filename, 'w') as file:
file.write(modified_content)
## Example usage
regex_file_edit('config.txt', r'version=\d+', 'version=2.0')
Safe File Modification Practices
Backup Before Editing
import shutil
def safe_file_modify(source_file):
## Create backup
backup_file = source_file + '.bak'
shutil.copy2(source_file, backup_file)
## Perform modifications
## ... modification logic here ...
Error Handling in File Editing
def robust_file_edit(filename):
try:
with open(filename, 'r+') as file:
## Editing operations
content = file.read()
## Modification logic
except PermissionError:
print(f"Cannot modify {filename}. Check permissions.")
except FileNotFoundError:
print(f"File {filename} not found.")
By mastering these techniques, LabEx developers can efficiently manipulate file contents with confidence and precision.