Python读取原子坐标txt文件 实现各原子坐标转独立列表的方法
读取原子坐标txt文件并输出指定格式
基础需求
编写代码读取存储原子坐标的txt文件,解析每个原子对应的坐标,按指定命名格式输出。
输入文件内容
坐标文件内容如下:
XYZ A 5.98974561 7.80124465 15.1032457 B 5.60245671 7.50214457 16.0012454
初始代码问题
最初编写的读取代码:
with open(filename) as f: while True: line = f.readlines() if not line: break print((line[1])) print((line[2]))
这段代码存在两个明显问题:
readlines()方法会一次性读取文件所有行,外层套while True死循环没有意义,还会导致重复读取- 没有对读取到的行内容做拆分、格式重组,只能输出原始行内容,达不到格式要求
运行初始代码得到的输出:
A 5.98974561 7.80124465 15.1032457 B 5.60245671 7.50214457 16.0012454
期望输出格式
A = [5.98974561 7.80124465 15.1032457] B = [5.60245671 7.50214457 16.0012454]
修正代码
仅实现指定格式打印
如果只需要在控制台输出要求的格式,使用以下代码即可:
# 替换为你的坐标文件实际路径 filename = "coords.txt" with open(filename, 'r', encoding='utf-8') as f: all_lines = f.readlines() # 跳过第一行的XYZ标识,从第二行开始遍历有效坐标行 for line in all_lines[1:]: line_content = line.strip() # 跳过空行 if not line_content: continue # 按空格拆分每行内容,第一部分是原子名,后面是坐标值 split_parts = line_content.split() atom_name = split_parts[0] coord_str = ' '.join(split_parts[1:]) print(f"{atom_name} = [{coord_str}]")
代码内存储坐标供后续计算
如果需要在后续代码中调用各个原子的坐标,不建议动态生成对应名称的变量,使用字典存储更规范易维护,示例代码:
filename = "coords.txt" atom_dict = {} with open(filename, 'r', encoding='utf-8') as f: all_lines = f.readlines() for line in all_lines[1:]: line_content = line.strip() if not line_content: continue split_parts = line_content.split() atom_name = split_parts[0] # 将坐标从字符串转为浮点数,方便后续计算 coords = [float(coord) for coord in split_parts[1:]] atom_dict[atom_name] = coords # 调用示例:获取A原子的x坐标直接用 atom_dict['A'][0] 即可
内容的提问来源于stack exchange,提问作者Isaac Danso Boateng
相关产品推荐
相关产品推荐

