如何根据 Z 值将 XYZ 文件解析为 3 个单独的文件?

How to parse an XYZ file into 3 separate files based on Z value?

我有一个 XYZ 文件,格式如下:

X[m] Y[m] DensA_1050c[m] DensB_1200c[m] DensC_1250c[m]
627841.54 231758.7 12.77 12.98 13.17
627841.54 231758.7 12.77 12.98 13.17
627841.54 231758.7 12.77 12.98 13.17
627841.54 231758.7 12.77 12.98 13.17

我正在寻找一种方法来读取 python 中的 XYZ 文件,然后将 XYZ 文件重新写入 3 个单独的 XYZ 文件,如下所示:

DensA_1050c[m]

X[m] Y[m] Z[m]
627841.54 231758.7 12.77
627841.54 231758.7 12.77
627841.54 231758.7 12.77
627841.54 231758.7 12.77

DensB_1200c[m]

X[m] Y[m] Z[m]
627841.54 231758.7 12.98
627841.54 231758.7 12.98
627841.54 231758.7 12.98
627841.54 231758.7 12.98

DensC_1250c[m]

X[m] Y[m] Z[m]
627841.54 231758.7 13.17
627841.54 231758.7 13.17
627841.54 231758.7 13.17
627841.54 231758.7 13.17

我尝试了以下代码来读取有效的 XYZ 文件,但我不知道如何像上面的示例那样解析它。

import numpy as np

file_location = 'C:/Users/Public/AllData.xyz'
xyz_file = np.genfromtxt(fname=file_location, skip_header=2, dtype='unicode')

print(xyz_file)

以上代码的结果是:

['627201.81' '233336.97' '12.94' '13.27' '13.41']

以下代码非常适合您的问题。用于输出文件名的行 headers 是 hard-coded 并映射到相应的列索引。

import numpy as np

file_location = 'AllData.xyz'
xyz_file = np.genfromtxt(fname=file_location, skip_header=2, dtype='unicode')

mappings = { 'DensA_1050c.xyz': 2, 'DensB_1200c.xyz' : 3, 'DensC_1250c.xyz' : 4 }

for mapping in mappings:
    with open(mapping, 'w') as output_file:
        for record in xyz_file:
            output_file.write(record[0])
            output_file.write('\t')
            output_file.write(record[1])
            output_file.write('\t')
            output_file.write(record[mappings[mapping]])
            output_file.write('\n')

DensA_1050c.xyz

627841.54   231758.7    12.77
627841.54   231758.7    12.77
627841.54   231758.7    12.77
627841.54   231758.7    12.77

DensB_1200c.xyz

627841.54   231758.7    12.98
627841.54   231758.7    12.98
627841.54   231758.7    12.98
627841.54   231758.7    12.98

DensC_1250c.xyz

627841.54   231758.7    13.17
627841.54   231758.7    13.17
627841.54   231758.7    13.17
627841.54   231758.7    13.17