"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Edit a Specific Line in a Text File Using Python?

How to Edit a Specific Line in a Text File Using Python?

Published on 2024-11-20
Browse:604

How to Edit a Specific Line in a Text File Using Python?

Editing Specific Line in Text File in Python

It is possible to edit a specific line in a text file in Python. To accomplish this, you can leverage the readlines() and writelines() methods.

To understand how to use these methods, consider a sample text file named "stats.txt":

Dan
Warrior
500
1
0

Opening the File and Reading Lines

You can open the file in read mode using open('stats.txt', 'r') and store it in a variable, such as file. The readlines() method on file reads all the lines in the file and returns them as a list:

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

Modifying a Specific Line

To modify a specific line, you can update the corresponding index in the data list. For instance, to replace "Warrior" in line 2 with "Mage," you would do the following:

data[1] = 'Mage\n'

Writing the Modified File

Once the line is modified, you can write the changes back to the file. Open the file in write mode using open('stats.txt', 'w') and use the writelines() method to write the modified data list to the file:

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

Note: Using a with block ensures proper file handling and automatically closes the file when the block is exited.

This approach allows you to edit a specific line in a text file by reading the entire file into a list, modifying the desired line, and then writing the modified list back to the file.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3