简体   繁体   中英

How to append values as a new coloumn to existing text file using python

I tried to append values to a file. First I unpack values from i, j from frozen set and then I append those values to a file. Again I need to append x values in another column rather than at the end of file. Kindly help me in this regard.

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'))

Output file:

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

Desired Output :

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

You can create 3 columns in one pass, so there is no need to "append" anything. It is like:

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)

If you want to append another column to the file created above, you need to read the lines from the file, append the text to each line, and write them back to the file.

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

If you want to append some value at the end of a line then, just do that.

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)

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM