Modifying Lines in a File In-Place
Can you parse a file line by line and edit lines on the go?
Yes, it is possible to simulate in-place editing using a backup file, similar to stdlib's fileinput module's approach.
Consider the following script:
import fileinput for line in fileinput.input(inplace=True, backup='.bak'): if some_condition(line): print(line, end='')
This script removes lines from the specified files that do not meet a certain condition, redirecting the modified content back into the original files.
For instance, to filter lines based on a condition in files first_file.txt and second_file.txt:
python grep_some_condition.py first_file.txt second_file.txt
After execution, first_file.txt and second_file.txt will contain only lines that satisfy the some_condition().
The above is the detailed content of How Can I Modify File Lines In-Place Efficiently?. For more information, please follow other related articles on the PHP Chinese website!