Modifying Lines in a File In-Place
Is it possible to sequentially parse a file line by line and modify lines in-place while iterating through the file?
Answer:
Yes, this can be simulated through the use of a backup file, as implemented in the fileinput module within the Python standard library.
Example Code:
Consider the following script that removes lines that do not meet a specific condition specified by the some_condition function from provided files or standard input:
#!/usr/bin/env python # grep_some_condition.py import fileinput for line in fileinput.input(inplace=True, backup='.bak'): if some_condition(line): print(line, end="") # This outputs modified lines to the current file
Usage Example:
To utilize this script, execute the following command:
$ python grep_some_condition.py first_file.txt second_file.txt
Upon execution, both first_file.txt and second_file.txt will be modified to contain only lines that satisfy the some_condition predicate.
The above is the detailed content of Can I Modify File Lines In-Place While Iterating in Python?. For more information, please follow other related articles on the PHP Chinese website!