Home > Backend Development > Python Tutorial > How Can I Modify Lines in Files In-Place Using Python?

How Can I Modify Lines in Files In-Place Using Python?

Susan Sarandon
Release: 2024-12-04 21:48:15
Original
511 people have browsed it

How Can I Modify Lines in Files In-Place Using Python?

Modifying Lines in Files In-Place

Parsing files line by line provides a valuable capability for manipulating content. However, if the need arises to edit lines within the file as you traverse them, you may wonder if this is achievable.

Inline Editing

Traditionally, modifying files in-place has not been a straightforward task. However, a simulation technique utilizing backup files, similar to the approach taken by Python's fileinput module, can provide a solution.

Example Script

Consider this example script:

#!/usr/bin/env python
import fileinput

for line in fileinput.input(inplace=True, backup='.bak'):
    if some_condition(line):
        print line, # this goes to the current file
Copy after login

In this script, we read from files provided on the command line or stdin using fileinput.input. By specifying inplace=True, we enable the modification of the current file. The backup parameter creates a backup file with a .bak extension.

Operation

As the script iterates through each line, it evaluates a given condition (some_condition) on each line. If the condition is met, the line is printed back to the current file, effectively modifying it in-place.

Example Usage

For instance, running the script with:

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

will result in first_file.txt and second_file.txt containing only lines that satisfy the some_condition() predicate.

The above is the detailed content of How Can I Modify Lines in Files In-Place Using 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