[英]Can you delete all the lines of a .txt file after a specific line?
我试图在包含特定字符串的行之后删除文本文件中的所有行。 我想要做的是找到所述文件中的行号并重写整个文本直到该行。
我正在尝试的代码如下:
import itertools as it
with open('sampletext.txt', "r") as rf:
for num, line in enumerate(rf, 1): #Finds the number of the line in which a specific string is contained
if 'string' in line:
print(num)
with open('sampletext_copy.txt', "w") as wf:
for line in it.islice(rf, 0, num):
wf.write(line)
也将不胜感激有关如何做到这一点的任何提示。 谢谢!
你可以这样做:
with open('sampletext.txt', "r") as rf, open('sampletext_copy.txt', "w") as wf:
for line in rf:
if 'string' in line:
break
wf.write(line)
基本上,您同时打开两个文件,然后逐行读取输入文件。 如果string
在该行中,那么您就完成了 - 否则,将其写入输出文件。
如果您想对原始文件应用更改,可以使用文件对象的.truncate()
方法:
with open(r"sampletext.txt", "r+") as f:
while line := f.readline():
if line.rstrip() == "string": # line.startswith("string")
f.truncate(f.tell()) # removes all content after current position
break
在这里,我们迭代文件直到到达此特定行并将流调整为我们已经读取的字节大小(为了获得它,我们使用.tell()
) 。
只是为了补充甜甜圈的答案,如果你想修改的地方文件,有一个更有效的解决方案:
with open('sampletext.txt', "r+") as f:
for line in iter(f.readline, ''): # Can't use for line in f: because it disables
# tell for txt
# Or for walrus lovers:
# while line := f.readline():
if 'string' in line:
f.seek(0, 1) # Needed to ensure underlying handle matches logical read
# position; f.seek(f.tell()) is logically equivalent
f.truncate()
break
如果问题 #26158得到修复(因此在文件上调用truncate
实际上是在逻辑位置truncate
s,而不是可能由于缓冲而大幅提升的底层原始句柄的任意位置),这个更简单的代码将起作用:
with open('sampletext.txt', "r+") as f:
for line in f:
if 'string' in line:
f.truncate()
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.