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.
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!