How to Replace Text in a Specific Line of a Text File Using Python?

Barbara Streisand
Release: 2024-11-16 14:13:03
Original
334 people have browsed it

How to Replace Text in a Specific Line of a Text File Using Python?

Editing Lines in Text Files with Python

In Python, working with text files often requires modifying specific lines. Here's how you can achieve this:

Question:

Consider a text file with the contents:

Dan
Warrior
500
1
0
Copy after login

How can we replace "Warrior" in line 2 with "Mage"?

Answer:

To modify a specific line in a text file, you need to follow these steps:

  1. Read the File:

    with open('stats.txt', 'r') as file:
        data = file.readlines()
    Copy after login

    This reads the file's contents into a list of lines.

  2. Modify the Line:

    data[1] = 'Mage\n'
    Copy after login

    Here, we assign the replacement line to the index corresponding to line 2 (remember Python arrays start from 0).

  3. Write Back to File:

    with open('stats.txt', 'w') as file:
        file.writelines(data)
    Copy after login

    This overwrites the original file with the modified contents.

Reasoning:

Direct line editing is impossible in files due to the overwriting nature of file systems. Instead, we read the entire file, modify the desired line in memory, and then overwrite the file with the updated contents.

The above is the detailed content of How to Replace Text in a Specific Line of 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