用于删除2个具体字符串

时间:2017-10-30 12:11:32

标签: python

我已经整理了一个读取文本文件的脚本,如下所示

*NODE
100000,1144.,-447.2639,339.0315
100001,1144.,-454.7716,342.956
100003,1144.,-448.2677,343.6241
100004,1144.,-454.8527,338.5432
*ELEMENT, TYPE=C3D6
228888,103103,103111,106773,186164,186165,196339
228889,103111,103232,106773,186165,186184,196339
228890,106773,106911,106912,196339,196457,196453

仅写入

228888,103103,103111,106773,186164,186165,196339
228889,103111,103232,106773,186165,186184,196339
228890,106773,106911,106912,196339,196457,196453

但实际上我想要它写

*ELEMENT, TYPE=C3D6
228888,103103,103111,106773,186164,186165,196339
228889,103111,103232,106773,186165,186184,196339
228890,106773,106911,106912,196339,196457,196453

下面是我写的代码,

with open('shell.txt', 'r') as oldfile, open('new_shell.txt', 'w') as newfile:
    for line in oldfile:
        if writing:
            if "*NODE" in line:
                writing = False
            else:
                newfile.write(line)
        elif "*ELEMENT" in line:
            writing = True
newfile.write

2 个答案:

答案 0 :(得分:1)

UIApplication.shared.keyWindow?.rootViewController = UIViewController()

您没有编写包含* ELEMENT的行。但我建议一般使用正则表达式/一些shell脚本来完成所有这些。

答案 1 :(得分:0)

在行中找到“* ELEMENT”时添加额外的write(line)

# init conditions
writing = False

with open('shell.txt', 'r') as oldfile, open('new_shell.txt', 'w') as newfile:
    for line in oldfile:
        if writing:
            if "*NODE" in line:
                writing = False
            else:
                newfile.write(line)
        elif "*ELEMENT" in line:
            newfile.write(line)
            writing = True

newfile.write