How to Modify Specific Lines in Text Files with Python?

Mary-Kate Olsen
Release: 2024-11-25 16:24:11
Original
406 people have browsed it

How to Modify Specific Lines in Text Files with Python?

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

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

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

Finally, write the modified list of lines back to the file:

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

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!

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