Editing File Lines In-Place
It is not possible to directly edit a line in-place while parsing a file line by line using standard Python functions. However, it is possible to simulate in-place editing using a backup file.
The fileinput Module
The fileinput module provides a way to simulate in-place editing. It works by:
In-Place Line Editing Example
Here's an example script that removes lines that do not satisfy a some_condition predicate from files specified on the command line or stdin:
#!/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, # this goes to the current file
Usage:
$ python grep_some_condition.py first_file.txt second_file.txt
After running this script, first_file.txt and second_file.txt will only contain lines that satisfy the some_condition() predicate.
The above is the detailed content of How Can I Edit File Lines In-Place Using Python?. For more information, please follow other related articles on the PHP Chinese website!