[英]Replace only first line of text file in python
I have a text file which consists of many lines of text. 我有一个包含多行文本的文本文件。
I would like to replace only the first line of a text file using python v3.6 regardless of the contents. 我想使用python v3.6只替换文本文件的第一行,而不管其内容如何。 I do not need to do a line-by-line search and replace the line accordingly.
我不需要逐行搜索并相应地替换该行。 No duplication with question Search and replace a line in a file in Python
与问题无重复搜索并替换Python文件中的一行
Here is my code; 这是我的代码;
import fileinput
file = open("test.txt", "r+")
file.seek(0)
file.write("My first line")
file.close()
The code works partially. 该代码部分起作用。 If the original first line has string longer than
"My first line"
, the excess sub-string still remains. 如果原始第一行的字符串长于
"My first line"
,则多余的子字符串仍然保留。 To be clearer, if original line is "XXXXXXXXXXXXXXXXXXXXXXXXX"
, then the output will be "My first lineXXXXXXXXXXXXXX"
. 为了清楚
"My first lineXXXXXXXXXXXXXX"
,如果原始行是"XXXXXXXXXXXXXXXXXXXXXXXXX"
,那么输出将是"My first lineXXXXXXXXXXXXXX"
。 I want the output to be only "My first line"
. 我希望输出仅是
"My first line"
。 Is there a better way to implement the code? 有没有更好的方法来实现代码?
You can use the readlines and writelines to do this. 您可以使用readlines和writelines来做到这一点。 For example, I created a file called "test.txt" that contains two lines (in Out[3]).
例如,我创建了一个名为“ test.txt”的文件,其中包含两行(在Out [3]中)。 After opening the file, I can use f.readlines() to get all lines in a list of string format.
打开文件后,我可以使用f.readlines()来获取字符串格式列表中的所有行。 Then, the only thing I need to do is to replace the first element of the string to whatever I want, and then write back.
然后,我唯一需要做的就是将字符串的第一个元素替换为我想要的任何内容,然后回写。
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)
Reading and writing content to the file is already answered by @Zhang. @Zhang已回答读写文件内容。
I am just giving the answer for efficiency instead of reading all the lines. 我只是给出效率的答案,而不是阅读所有内容。
Use: shutil.copyfileobj 使用: 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.