python读取xyz文件

数据文件的处理以及小细节很影响科研进度,但又是必不可缺的。虽然遇到过多种多样的数据文件处理问题并得到解决,等到过一段时间又不知道如何解决了。

不断地把方法积累起来吧。

今天使用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()可以直接将空格替换掉,元素之间有多少个空格都可以,变成新建列表中的元素。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值