首頁  >  文章  >  後端開發  >  如何在 Python 中更新文字檔案中的特定行?

如何在 Python 中更新文字檔案中的特定行?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-14 22:59:02190瀏覽

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)

In this approach:

  • data = file.readlines() reads the file into a list of lines.
  • data[1] = 'Mage\n' 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.

以上是如何在 Python 中更新文字檔案中的特定行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn