如何使用python提取文件的特定部分?

时间:2018-11-07 00:43:06

标签: python

我正在尝试提取输出高斯计算(量子软件)的特定部分。这只是高斯输出的一小部分:

Title Card Required
-------------------
Symbolic Z-matrix:
Charge =  0 Multiplicity = 1
C                     1.96715   0.72663  -0.79025 
C                     0.96772  -0.1552   -0.04235 
H                     1.77953   0.68124  -1.86653 
H                     1.89494   1.76703  -0.46507 
H                     2.98192   0.36384  -0.60544 
C                     1.25535  -0.16874   1.46964 
H                     0.53919  -0.8003    2.00265 
H                     2.25947  -0.56688   1.6354 
H                     1.2242    0.83597   1.9091 
O                     1.11217  -1.46796  -0.58217 
H                     0.35795  -1.98625  -0.26491 
C                    -0.47408   0.32049  -0.35104 
H                    -0.65899   0.2864   -1.42804 
O                    -2.664    -0.43922  -0.23984 
O                    -1.32917  -0.6104    0.29914 
O                    -0.77574   1.63293   0.05613 
H                    -2.88162   0.44503   0.10828 
H                    -0.53949   1.71202   0.99234 

GradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGrad
Berny optimization.
Initialization pass.

这是我编写的代码:

import os
import glob                    


my_files = glob.glob('*.log')    
n2_file = "cart_coor.txt"
A = " Symbolic Z-matrix:"
B = " Add virtual bond connecting"
C = "     GradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGrad"
my_list = []
collector = []


for many_files in my_files:           
    with open (many_files, 'r') as in_file:
        with open (n2_file,'a+') as out_file:

            for line in in_file:
                if line.startswith(A):
                    my_list.append(line)

                    for line in in_file:
                        collector.append(line)

                        if line.startswith(B):
                            out_file.write(""+many_files.strip(".log")+"\n")
                            out_file.write("".join(my_list)+"".join(collector))

该代码适用于某些输出文件。但是,有些文件以(GradGradGrad)结尾,如果我选择它作为代码的结尾,则它将提取整个代码,而不是笛卡尔坐标(此处为Z矩阵)。使其适用于所有文件的最佳方法是什么?

0 个答案:

没有答案