简体   繁体   English

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM