如何使用 python 将值作为新列附加到现有文本文件

问题描述 投票:0回答:2

我尝试将值附加到文件中。首先,我从冻结集中解压缩 i、j 中的值,然后将这些值附加到文件中。我再次需要将 x 值附加到另一列而不是文件末尾。请在这方面帮助我。

from __future__ import print_function
from molmod import *
from molmod.bonds import bonds

import glob

for file in glob.glob("*.xyz"):

  mol = Molecule.from_file(file)
  mol.graph = MolecularGraph.from_geometry()
   
  bos = list(mol.graph.edges)
  
  for edge in bos:
    i, j = edge
    print(i, j, file = open(file.replace('xyz', 'txt'), 'a'))
    s = list(mol.graph.orders)
    for x in s:
           print(x, file = open(file.replace('xyz', 'txt'), 'a'))

输出文件:

4 5
1 2
2 3
1 4
4 6
6 7
0 1
8 9
8 10
10 11
11 13
13 15
16 15
16 17
8 6
10 2
11 12
13 14
18 19
18 20
25 20
25 27
16 18
27 15
21 22
21 23
24 21
20 21
25 26
27 28
1.0
2.0
1.0
2.0
2.0
1.0
1.0
1.0
2.0
1.0
1.0
1.0
2.0

所需输出:

4 5        1.0 
1 2        2.0
2 3        1.0
1 4        2.0
4 6        2.0
6 7        1.0
0 1        1.0
8 9        1.0
8 10       2.0
10 11      1.0
11 13      1.0
13 15      1.0
16 15      2.0
16 17      1.0
8 6        2.0
10 2       2.0
11 12      1.0
13 14      1.0
18 19      2.0
18 20      1.0
25 20      1.0
25 27      1.0
16 18      1.0
27 15      2.0
21 22      1.0
21 23      1.0
24 21      1.0
20 21      1.0
25 26      2.0
27 28      1.0
python for-loop glob
2个回答
1
投票

您可以一次性创建 3 列,因此无需“附加”任何内容。就像:

bos = list(mol.graph.edges)
s = list(mol.graph.orders)
f = open(file.replace('xyz', 'txt'), 'a')
for i in range(len(bos)):
    i, j = bos[i]
    print(i, j, s[i], file = f)

如果要将另一列附加到上面创建的文件中,则需要从文件中读取行,将文本附加到每行,然后将它们写回到文件中。

myNewData = [1, 2, 999, 444] #new data to append to an existing file

f = open(file.replace('xyz', 'txt'), 'r+')   #open an existing file
allLines = f.read().split("\n")    #read all lines from the file
f.seek(0)  #rewind the file pointer to start writing from the first line
for i in range(min(len(allLines), len(myNewData))):
    print(allLines[i], myNewData[i], file = f)   #append new data to each line
f.close()   #done

0
投票

如果您想在行尾附加一些值,就这样做。

with open(filename, "w") as f:  # open in write mode
  for x in s:
     x = str(x) + your_value + "\n"  # assuming x can be converted to string
     f.write(x)

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.