我需要帮助调整输出文件格式
我有一个文件,里面有两个表格。我想从第二个表格中提取第一个表格的值,然后把这些值写到另一个文件里。
这个文件有四列,第一列是符号,第二、第三和第四列是我想要相互减去的值。我希望这些值能够一个接一个地列出来。
这是我的Python 3脚本。
def read_xyz_file(file_path, start_line=2, end_line=None):
"""Reads an XYZ file amd returns a list of atomic coordinates"""
atomic_coordinates=[]
with open(file_path, 'r') as file:
lines=file.readlines()[start_line-1:end_line]
num_atoms=int(lines[0])
for line in lines[1:]:
line=line.split()
x=float(line[1])
y=float(line[2])
z=float(line[3])
atomic_coordinates.append([x,y,z])
return atomic_coordinates
def subtract_coordinates(file1_path, file2_path, output_path):
"""Subtract coordinates from file2 from coordinates in file1 and writes the results to file3"""
file1_coordinates=read_xyz_file(file1_path, start_line=3101, end_line=3124)
file2_coordinates=read_xyz_file(file2_path, start_line=3125, end_line=3148)
if len(file1_coordinates) !=len(file2_coordinates):
print("Error: Number oof atoms in file1 is not the same.")
return
num_atoms=23
with open(output_path, 'w') as file3:
file3.write(str(num_atoms)+"\n")
file3.write("Coordinates subtracted from file2-file1\n")
for i in range(num_atoms):
x_diff=file2_coordinates[i][0]-file1_coordinates[i][0]
y_diff=file2_coordinates[i][1]-file1_coordinates[i][1]
z_diff=file2_coordinates[i][2]-file1_coordinates[i][2]
file3.write("""{:.6f}\n""".format(x_diff)
"""{:.6f}\n""".format(y_diff)
"""{:.6f}\n""".format(z_diff))
file1_path="TS6-int-IRC-1.xyz"
file2_path="TS6-int-IRC-1.xyz"
output_path="file3.xyz"
subtract_coordinates(file1_path, file2_path, output_path)
当我运行这段代码时,得到了一个列表。但是在这个列表中,第一行的值是先列出来的,然后是第二行,依此类推。不过,我希望第二列的值先列出来,然后是第三列的值,依此类推。
输入示例:
文件1:
A | x | y | z |
---|---|---|---|
C | 25 | 11 | 6 |
C | 12 | 10 | 5 |
C | 5 | 2 | 1 |
文件2:
A | x | y | z |
---|---|---|---|
C | 32 | 10 | 6 |
C | 14 | 6 | 1 |
C | 2 | 8 | 7 |
我想要的输出(以列的形式,而不是行):
7.
2.
-3.
-1.
-4.
6.
0.
-1.
6.
我得到的输出(以列的形式,而不是行):
7.
-1.
0.
2.
-4.
1.
-3.
6.
6.
1 个回答
-2
你需要改变一下生成输出的循环方式。现在你用的是一个循环,它对每个原子进行遍历,并为每个原子生成一组三个输出。其实,你应该先选择一列,然后再对原子进行遍历,获取该列的输出。
所以,你的处理循环应该像这样:
with open(output_path, 'w') as file3:
file3.write(str(num_atoms)+"\n")
file3.write("Coordinates subtracted from file2-file1\n")
for column in range(3): # iterate through a column at a time
for i in range(num_atoms):
diff=file2_coordinates[i][column]-file1_coordinates[i][column]
file3.write("""{:.6f}\n""".format(diff))