如下图所示,有一行ENDMDL
。如何使用readline()
函数和一些基本循环删除此行后的所有内容?
答案 0 :(得分:1)
你走了:
file_path = 'your/file/path'
with open(file_path) as inf, open('outfile', 'w') as outf:
for i in inf:
if i.strip() == 'ENDMDL':
break
else:
outf.write(i)
答案 1 :(得分:-1)
使用tempfile
并使用shutil.move
替换原始内容:
from tempfile import NamedTemporaryFile
from shutil import move
with open("your_file") as f, NamedTemporaryFile("w", dir=".",delete=False) as tmp:
for line in f:
tmp.write(line)
if line.rstrip() == "ENDMDL":
break
move(tmp.name, "your_file")