Home  >  Article  >  Backend Development  >  How to Replace Text in a Specific Line of a Text File Using Python?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 14:13:03335browse

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

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()

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

  2. Modify the Line:

    data[1] = 'Mage\n'

    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)

    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!

Statement:
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