Home > Backend Development > Python Tutorial > How Can I Efficiently Replace Lines in a Text File Using Python?

How Can I Efficiently Replace Lines in a Text File Using Python?

Mary-Kate Olsen
Release: 2024-12-20 09:00:18
Original
707 people have browsed it

How Can I Efficiently Replace Lines in a Text File Using Python?

Replacing Lines in a Text File Efficiently

To replace specific lines within a text file in Python, consider the use of the fileinput module. This method avoids loading the entire file into memory, making it efficient for large files.

Using fileinput

import fileinput

with fileinput.input("test.txt", inplace=True) as f:
    for line in f:
        if "foo" in line:
            print(line.replace("foo", "bar"), end='')
Copy after login

With this code, the original file is renamed to a backup, and the standard output is redirected to write into the original file within the loop. Any print statements inside the loop modify the file's contents directly.

Explicit File Manipulation

For readability, consider these explicit options:

Option 1 (For Small Files):

with open("test.txt", "r") as f:
    lines = f.readlines()

with open("test.txt", "w") as f:
    for line in lines:
        if "foo" in line:
            f.write(line.replace("foo", "bar"))
        else:
            f.write(line)
Copy after login

Option 2 (For Large Files):

import tempfile

with open("test.txt") as original, tempfile.NamedTemporaryFile(delete=False) as temp:
    for line in original:
        if "foo" in line:
            temp.write(line.replace("foo", "bar").encode())
        else:
            temp.write(line.encode())

temp.flush()
os.replace(temp.name, "test.txt")
Copy after login

The above is the detailed content of How Can I Efficiently Replace Lines in a Text File 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