如何使用python删除测试文件中的后一部分内容?

2024-06-16 08:42:28 发布

您现在位置:Python中文网/ 问答频道 /正文

正如下面的图片,有一行ENDMDL。如何使用readline()函数和一些基本循环来删除此行之后的所有内容

enter image description here


Tags: 函数内容readline图片endmdl
2条回答

给你:

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)

使用tempfileshutil.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")

相关问题 更多 >