Home > Backend Development > Python Tutorial > Can I Modify File Lines In-Place While Iterating in Python?

Can I Modify File Lines In-Place While Iterating in Python?

Patricia Arquette
Release: 2024-12-04 13:24:11
Original
732 people have browsed it

Can I Modify File Lines In-Place While Iterating in Python?

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
Copy after login

Usage Example:

To utilize this script, execute the following command:

$ python grep_some_condition.py first_file.txt second_file.txt
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template