Home > Backend Development > Python Tutorial > How to Edit a Specific Line in a Text File Using Python?

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

Susan Sarandon
Release: 2024-11-14 10:08:01
Original
188 people have browsed it

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
Copy after login

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()
Copy after login

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'
Copy after login

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)
Copy after login

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.

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