我有一个文本文件,它由许多行文本组成。
我只想使用Pythonv3.6替换文本文件的第一行,而不考虑内容。我不需要逐行搜索并相应地替换行。无重复问题Search and replace a line in a file in Python
这是我的密码;

import fileinput

file = open("test.txt", "r+")
file.seek(0)
file.write("My first line")

file.close()

代码部分工作。如果原始第一行的字符串长度大于"My first line",则剩余的子字符串仍将保留。为了更清楚,如果原始行是"XXXXXXXXXXXXXXXXXXXXXXXXX",那么输出将是"My first lineXXXXXXXXXXXXXX"我只希望输出"My first line"。有没有更好的方法来实现代码?

最佳答案

您可以使用readlines和writelines来执行此操作。
例如,我创建了一个名为“test.txt”的文件,其中包含两行(in Out[3])。打开文件后,我可以使用f.readlines()获取字符串格式列表中的所有行。然后,我只需要将字符串的第一个元素替换为我想要的任何内容,然后写回。

with open("test.txt") as f:
    lines = f.readlines()

lines # ['This is the first line.\n', 'This is the second line.\n']

lines[0] = "This is the line that's replaced.\n"

lines # ["This is the line that's replaced.\n", 'This is the second line.\n']

with open("test.txt", "w") as f:
    f.writelines(lines)

10-07 19:08
查看更多