数据文件的处理以及小细节很影响科研进度,但又是必不可缺的。虽然遇到过多种多样的数据文件处理问题并得到解决,等到过一段时间又不知道如何解决了。
不断地把方法积累起来吧。
今天使用python读取xyz文件,想要返回原子数目和坐标,但是坐标之间并不是被一个空格分开而是数个空格。最后chatgpt给出了方法!
import numpy as np
def read_xyz(filename):
"""
Read XYZ file and return atom names and coordinates.
Parameters:
- filename: Path to the XYZ file.
Returns:
- atom_names: List of atom names.
- coordinates: 2D numpy array of coordinates.
"""
with open(filename, 'r') as file:
num_atoms = int(file.readline()) # Read the number of atoms
file.readline() # Skip the comment line
# Initialize lists to store atom names and coordinates
atom_names = []
coordinates = []
# Read atom names and coordinates
for line in file:
atom_info = line.split()
atom_names.append(atom_info[0])
coordinates.append([float(x) for x in atom_info[1:]])
return atom_names, np.array(coordinates)
# Example usage:
filename = 'your_xyz_file.xyz'
atom_names, coordinates = read_xyz(filename)
print("Atom names:", atom_names)
print("Coordinates:\n", coordinates)
让我学习到的两点如下:
1. file.readline()命令运行后再次运行是从下一行开始读取。
2. line.split()可以直接将空格替换掉,元素之间有多少个空格都可以,变成新建列表中的元素。