如何使用python将文本块从一个文件“复制粘贴”到另一个文件?

2024-05-05 06:01:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一些分子模拟,我有一个带有坐标的文件(一个.xyz文件,基本上是一个带有选项卡列的文件),我需要向它发送另一个文件,它将是我模拟的输入文件

为了给你一张图片,这是我的输入文件在坐标下的样子(底部还有更多的东西保持不变): inputfile.py

# One-electron Properties
# Methacrylic acid (MA0)
# Neutral
# 86.09 g/mol
memory 8 GB
molecule MA0 {
0 1
  C          2.87618       -0.84254        0.16797
  C          2.96148        0.13611        1.08491
  C          2.43047       -0.01082        2.47698
  C          3.62022        1.40750        0.67356
  O          3.45819        2.47668        1.24567
}
.
.
.

我已经在另一个文件中生成了一些坐标。该文件看起来像: conformer_coords.xyz

15
conformer index = 0001, molecular weight is = 100.052429496, MMA.pdb
O          2.98687        0.35207        1.05259
C          2.40900        0.04400        0.02100
O          1.13058        0.37171       -0.29283
C          0.85476        1.77012       -0.33847
.
.
.

我要做的是将inputfile.py中的坐标替换为conformer_coords.xyz中的坐标。我的conformer中的坐标位置数是已知的。现在让我们称之为N。所以,conformer_coords.xyz有N+2行

我基本上想从conformer_coords.xyz获取坐标,并将它们放在

{
0 1

}(是的,那里需要0 1

我该怎么做?python能做到吗?无论如何,我都在使用子流程,所以如果awk或bash能够做到这一点,如果有人能给我指出正确的方向,我将非常感激


Tags: 文件py图片propertiescoordsone分子选项卡
1条回答
网友
1楼 · 发布于 2024-05-05 06:01:33
import re
def insert_data(conformer_filepath,input_filepath,output_filepath):
    #grab conformer data
    with open(conformer_filepath,'r') as f:
        conformer_text = f.read()
    conformer_data = re.search('conformer[^\n]+\n(.+)',conformer_text,re.M|re.S).group(1)
    #this looks for the line that has conformer in it and takes all lines after it
    
    #grab input file before and after text
    with open(input_filepath,'r') as f:
        input_text = f.read()
    input_pre,input_post = re.search('(^.+\n0 1\n).+?(\n}.*)$',input_text,re.M|re.S).groups()
    #this looks for the "0 1" line and takes everything before that. Then it skips down to the next curly bracket which is at the start of a line and takes that and everything past it.

    #write them to the output file
    with open(output_filepath,'w') as f:
        f.write(input_pre + conformer_data + input_post)
        #this writes the three pieces collected to the output file

相关问题 更多 >