[英]How to use python to delete the latter part of the content in a test file?
Just as the picture below, there is a line ENDMDL
.如下图,有一行
ENDMDL
。 How can I use the readline()
function and some basic loop to delete all the content after this line?如何使用
readline()
函数和一些基本循环删除此行之后的所有内容?
Here you go:干得好:
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)
Use a tempfile
and use shutil.move
to replace the original:使用
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.