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:
Read the File:
with open('stats.txt', 'r') as file: data = file.readlines()
This reads the file's contents into a list of lines.
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).
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!