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

2024-05-19 16:26:46 发布

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

我试图将值附加到文件中。首先,我从冻结集中解包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

14

4.6

6 7

01

8.9

810

10 11

11 13

13 15

16 15

16 17

8.6

102

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

12.0

2 3 1.0

1 4 2.0

4.6.2.0

671.0

01.0

891.0

8102.0

10111.0

11 13 1.0

13 15 1.0

16152.0

16171.0

8.6.2.0

102.0

11121.0

13141.0

18 19 2.0

18201.0

25 20 1.0

25 27 1.0

16181.0

27 15 2.0

21221.0

21231.0

24211.0

20 21 1.0

25 26 2.0

27 28 1.0


Tags: 文件infromimportforgloblistfile
2条回答

您可以在一次过程中创建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

如果您想在一行的末尾附加一些值,那么就这样做

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)

希望有帮助

相关问题 更多 >