繁体   English   中英

仅替换python中文本文件的第一行

[英]Replace only first line of text file in python

我有一个包含多行文本的文本文件。

我想使用python v3.6只替换文本文件的第一行,而不管其内容如何。 我不需要逐行搜索并相应地替换该行。 与问题无重复搜索并替换Python文件中的一行

这是我的代码;

import fileinput

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

file.close()

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

您可以使用readlines和writelines来做到这一点。 例如,我创建了一个名为“ test.txt”的文件,其中包含两行(在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)

@Zhang已回答读写文件内容。

我只是给出效率的答案,而不是阅读所有内容。

使用: shutil.copyfileobj

from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM