Home > Backend Development > Python Tutorial > How Can I Edit File Lines In-Place Using Python?

How Can I Edit File Lines In-Place Using Python?

Susan Sarandon
Release: 2024-12-03 16:38:12
Original
436 people have browsed it

How Can I Edit File Lines In-Place Using Python?

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:

  • Creating a backup file with the extension specified by the backup parameter (default: '.bak').
  • Reading from the backup file instead of the original file.
  • Writing to the original file when the inplace parameter is set to True.

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

Usage:

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

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!

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