如何修改Python代码批量读取surf_001至surf_100下的a.xyz并统计含H行数
批量读取多目录下a.xyz文件的修改方案
原代码核心问题
- 路径采用硬编码写死
surf_001层级,没有建立跨目录的匹配规则,自然只能检索到第一个文件夹的目标文件 - H原子计数变量定义在文件遍历循环外层,会跨文件累加所有统计值,无法实现单个文件的独立计数
推荐修改方案(自动匹配所有符合命名规则的目录)
不需要手动遍历1到100的编号,直接通过glob通配符匹配所有surf_*开头的目录,只要目录命名符合要求,哪怕后续扩展到surf_200、surf_500都能自动识别,无需改动代码。
修改后的完整可运行代码:
import numpy as np import glob import os # 定义根目录 root_path = '/home/sg/scratch/slabs/cool_100' # 通配匹配所有surf_开头目录下的a.xyz文件 target_files = glob.glob(os.path.join(root_path, 'surf_*', 'a.xyz')) print(f"共检索到{len(target_files)}个目标文件:{target_files}") oh_den = [] # 逐个处理匹配到的文件 for file in target_files: # 单文件计数前重置计数器,避免累加 h_count = 0 with open(file, 'r') as f: file_content = f.readlines() for line in file_content: if 'H' in line: h_count += 1 # 记录当前文件所属目录和对应的计数结果 current_dir = os.path.basename(os.path.dirname(file)) oh_den.append( (current_dir, h_count) ) print(f"{current_dir} 目录下a.xyz的H原子数量:{h_count}")
可选方案(精准控制读取范围)
如果需要严格限定读取的目录编号范围(比如只处理surf_001到surf_100,跳过其他命名的surf目录),可以通过循环生成带补零的目录名的方式实现,同时增加文件存在判断,避免单个文件缺失导致程序崩溃:
import os root_path = '/home/sg/scratch/slabs/cool_100' oh_den = [] # 遍历编号范围1到100,对应surf_001到surf_100 for num in range(1, 101): # 按3位数字补零生成目录名 surf_name = f"surf_{str(num).zfill(3)}" target_file = os.path.join(root_path, surf_name, 'a.xyz') # 仅在文件真实存在时执行统计 if os.path.isfile(target_file): h_count = 0 with open(target_file, 'r') as f: for line in f: if 'H' in line: h_count += 1 oh_den.append( (surf_name, h_count) ) print(f"{surf_name} 目录下a.xyz的H原子数量:{h_count}")
注意:两种方案均保留了你原代码中统计H原子数的核心逻辑,没有改动原有统计规则,仅补全了多目录遍历和计数隔离的能力。
内容的提问来源于stack exchange,提问作者Xdrake
相关产品推荐
相关产品推荐

