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

How to Update a Specific Line in a Text File in Python?

Mary-Kate Olsen
Release: 2024-11-14 22:59:02
Original
277 people have browsed it

How to Update a Specific Line in a Text File in Python?

Editing a Specific Line in a Text File in Python

You have a text file containing lines of data, and you need to update a specific line, say the second one, with a new value. You may have tried using "myfile.writelines('Mage')[1]" but it produced an incorrect result.

The key to editing a specific line in a text file is to load the entire file into memory and manipulate it as a list of lines. Here's how to do it:

# Read the file into a list of lines
with open('stats.txt', 'r') as file:
    data = file.readlines()

# Make the desired edit. Here, we're changing line 2 to 'Mage'.
data[1] = 'Mage\n'

# Write the updated list of lines back to the file
with open('stats.txt', 'w') as file:
    file.writelines(data)
Copy after login

In this approach:

  • data = file.readlines() reads the file into a list of lines.
  • data[1] = 'Magen' updates the second line with 'Mage'.
  • with open('stats.txt', 'w') as file: opens the file for writing and rewrites the entire contents with the updated line.

The reason behind this approach is that you cannot directly edit a specific line in a text file. The file can only be overwritten by entire lines, so rewriting the entire file with the updated line is necessary.

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