python - 将文本从文件复制到另一个文件并编辑生成的文件
问题描述
我正在尝试编写一个函数,该函数将使用另一个文件中的文本生成一系列文件。我遇到的问题是我想将文本添加到从文件写入的行的末尾。除此之外,我希望添加的文本取决于我所在的行。
源文件如下所示:
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)
但是,我不确定如何添加最后两列。
有什么建议么?
解决方案
如果我正确理解了您的问题,那么您可以执行以下操作:
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)
希望这就是你的意思!!
推荐阅读
- reactjs - 将 React 应用程序部署到 Firebase 后出现 Git 错误
- java - 为什么 Eclipse 显示错误“
设置为真”而我将其设置为假? - javascript - 脚本是否总是在遇到循环时执行完整长度的循环,然后再继续执行其后的语句?
- javascript - 如何在 React 中创建下载按钮
- javascript - Node-red:从 msg.payload 获取值并将其保存在变量中
- c# - 如何解决此视觉工作室错误?“无法对打开了用户映射部分的文件执行请求的操作”
- python - Aur 包显示权限被拒绝{已解决}
- python - 对非常大的离散值样本数据集进行聚类
- bash - 无论上下文如何,有没有办法在 Bash 中获取绝对行号?
- pine-script - 我需要输入条形索引偏移值