import os

def extract_coordinates(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        
        # 寻找包含特定标识符的行
        for i, line in enumerate(lines):
            if "Generated by Multiwfn" in line:
                start_index = i + 2  # 索引行在包含标识符的行的下两行
                break
        
        # 提取元素类型和坐标
        coordinates = []
        for line in lines[start_index:]:
            if line.strip():  # 跳过空行
                parts = line.split()
                if len(parts) >= 4:
                    element = parts[0]
                    x, y, z = map(float, parts[1:4])
                    coordinates.append((element, x, y, z))
        
        return coordinates

def main():
    folder_path = 'xyz'
    output_file = 'xyz.txt'

    # 获取文件夹中所有.gjf文件的路径并排序
    gjf_files = sorted([f for f in os.listdir(folder_path) if f.endswith('.gjf')])
    
    # 打开输出文件
    with open(output_file, 'w') as out:
        for file_name in gjf_files:
            file_path = os.path.join(folder_path, file_name)
            # 提取文件中的元素类型和坐标
            coordinates = extract_coordinates(file_path)
            # 将文件名去除后缀添加到提取内容之前
            out.write(f'{os.path.splitext(file_name)[0]}\n')
            # 将提取的信息写入输出文件
            for element, x, y, z in coordinates:
                out.write(f'{element} {x} {y} {z}\n')
            out.write('\n')

    print(f'Coordinates extracted from {len(gjf_files)} files and saved to {output_file}')

if __name__ == "__main__":
    main()
