Editing Specific Lines in Text Files with Python
In this code snippet, you're trying to modify a specific line in 'stats.txt', but the approach you're using is incorrect. Fortunately, there's a Pythonic way to accomplish this task.
Firstly, open the file using a 'with' statement:
with open('stats.txt', 'r') as file:
This ensures that the file is properly handled and closed when the operation is complete.
Next, read all the lines of the file into a list using 'readlines()':
data = file.readlines()
This effectively loads the entire file contents into memory.
Now, you can modify the desired line by indexing the 'data' list:
data[1] = 'Mage\n' # Change "Warrior" in line 2 to "Mage"
Finally, write the modified list of lines back to the file:
with open('stats.txt', 'w') as file: file.writelines(data)
By loading the entire file into memory, you can manipulate specific lines effectively without having to overwrite the entire file. This technique is particularly useful for making multiple modifications to a file or if you need to preserve the file's existing contents.
The above is the detailed content of How to Modify Specific Lines in Text Files with Python?. For more information, please follow other related articles on the PHP Chinese website!