[英]How to append/update new values to the rows of a existing csv file from a new csv file as a new column in python using pandas or something else
[英]How to append values as a new coloumn to existing text file using 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
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
您可以一次創建 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)
希望有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.