用Python编写文件的一部分

时间:2018-08-08 12:18:37

标签: python

我有一个文件,其中包含此结构模型的信息,重复1到100:

MODEL       <Number>
.....
.....
.....
ENDMDL

每个模型都有一个数字。模型信息以行MODEL <Number>开始,以行ENDMDL结尾。

我只想向一个新文件中写入一个型号。

1 个答案:

答案 0 :(得分:0)

此代码将提取所有模型

  • 读取整个文件
  • 使用正则表达式将模型文本和模型编号提取为元组
  • 为生成的元组创建字典条目
  • 将所有模型写为单个文件

您可以将其调整为只写一个数字。

编写演示数据:

code = """MODEL       0
..0...
..0...
..0...
ENDMDL
MODEL       1
..1...
..1..
..1...
ENDMDL
"""

with open("f.txt" , "w") as w:
    w.write(code)

读取和解析演示数据:

import re

with open("f.txt", "r") as r:
    allModels = r.read()

allM = {}

# the regex captures as few as possible things between 
# MODEL and ENDMDL and captures the first number after 
# MODEL as your modelnumber.

for m in re.findall(r"(MODEL\s+(\d+).+?ENDMDL)",allModels,re.DOTALL):
    # create a dictionary entry for each found match-tuple
    allM[int(m[1])] = m[0]

print(allM)

for k in allM:
    with open("model_{}.txt".format(k),"w") as w:
        w.write(allM[k])

(字典的)输出:

{0: 'MODEL       0\n..0...\n..0...\n..0...\nENDMDL', 
 1: 'MODEL       1\n..1...\n..1..\n..1...\nENDMDL'}