Home >Backend Development >Python Tutorial >How Can I Modify File Lines In-Place Efficiently?

How Can I Modify File Lines In-Place Efficiently?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 11:04:10611browse

How Can I Modify File Lines In-Place Efficiently?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn