首页 > 解决方案 > 将文本从文件复制到另一个文件并编辑生成的文件

问题描述

我正在尝试编写一个函数,该函数将使用另一个文件中的文本生成一系列文件。我遇到的问题是我想将文本添加到从文件写入的行的末尾。除此之外,我希望添加的文本取决于我所在的行。

源文件如下所示: C1 1.00964527 -0.31216598 -0.03471416 C2 2.46197796 -0.03537534 -0.02239528 C3 3.13892016 -1.29949550 -0.01824029 N1 0.78031101 -1.74687208 -0.03258816 N2 2.41533961 -3.71674253 -0.03080008 H1 6.38746003 -0.16735186 0.01037509 H2 5.06643233 -2.35376889 -0.00392019 H3 2.64230377 2.15284044 -0.01822299 Cu1 -0.97960685 -2.67533229 -0.06199922 目标是生成一个输出文件,该文件在末尾有两列附加列,其中新列的值将通过函数的输入来确定。 C1 1.00964527 -0.31216598 -0.03471416 6 32 C2 2.46197796 -0.03537534 -0.02239528 4 32 C3 3.13892016 -1.29949550 -0.01824029 4 32 N1 0.78031101 -1.74687208 -0.03258816 7 32 N2 2.41533961 -3.71674253 -0.03080008 7 32 H1 6.38746003 -0.16735186 0.01037509 1 32 H2 5.06643233 -2.35376889 -0.00392019 1 32 H3 2.64230377 2.15284044 -0.01822299 1 32 Cu1 -0.97960685 -2.67533229 -0.06199922 29 32 以下代码部分复制源文件的内容并将它们粘贴到输出文件中。

def makeGNDrun(fname, aname, nAtoms):
    i = 1
    for i in range(1, nAtoms + 1):

        f = open(str(aname) + str(i) + "_gnd.run", "w+")

        with open(fname + ".xyz") as f:
            with open(aname + str(i) + "_gnd.run", "a+") as f1:
                for line in f:
                    f1.write(line)

但是,我不确定如何添加最后两列。

有什么建议么?

标签: pythontextwrite

解决方案


如果我正确理解了您的问题,那么您可以执行以下操作:

def makeGNDrun(fname, aname, nAtoms):
    for i in range(1, nAtoms + 1):

        # open two files together... first in read-mode and the other in append-mode
        with open(str(aname) + str(i) + "_gnd.run", "r") as f, \
             open(aname + str(i) + "_gnd.run", "a") as f1:

             # iterate over lines of f which is in read-mode
             for line in f.readlines():
                 # line is read from f, so you can modify it before writting it to f1
                 # here I will append " i  32" to it
                 line = line.strip() + '\t' + str(i) + '\t' + str(32) + '\n'
                 f1.write(line)

希望这就是你的意思!!


推荐阅读