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

时间:2015-11-30 03:46:43

标签: python python-3.x

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

enter image description here

2 个答案:

答案 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")