我正在尝试将数据存储在数组/列表中。但是,由于我在python中的经验有限,不能那样做。正如您所看到的,目前,我最多可以将它们写入文件,但是对于后期处理,我需要在numpy / scipy数组中读取它们。 我怎么能这样做?
for subdir, dirs, files in os.walk(sys.argv[1]):
for inp in files:
if inp.endswith("_SCF.out"):
fsys = subdir + "/" + inp
with open(fsys) as finp:
for line in finp:
if "lattice constant ALAT" in line:
lata = float(line.strip()[-7:])/1.88973
if " ERR " in line:
mom = line.strip()[61:70]
if "SCF - cycle converged" in line:
etot = float(line.lstrip()[10:25])
of.write("{:<10f} {:<15f} {:<15f}\n"
.format(lata, etot, float(mom)))
注意:另外,就像ERR
一样,我有很多行匹配。我会拿起最后一张这样的地图。
这是一个新手问题,但需要帮助。可能是我遗失了一些东西,但在SO中找不到任何答案。
编辑在@ cel的评论之后编辑的完整代码是:
#!/usr/bin/python3
import os
import sys
import numpy as np
data = []
# print(sys.argv[1])
fout = sys.argv[1] + "_trial.dat"
with open(fout, "w") as of:
for subdir, dirs, files in os.walk(sys.argv[1]):
for inp in files:
if inp.endswith("_SCF.out"):
fsys = subdir + "/" + inp
# print(fsys)
with open(fsys) as finp:
for line in finp:
if "lattice constant ALAT" in line:
lata = float(line.strip()[-7:])/1.88973
if " ERR " in line:
mom = line.strip()[61:70]
if "SCF - cycle converged" in line:
etot = float(line.lstrip()[10:25])
of.write("{:<10f} {:<15f} {:<15f}\n"
.format(lata, etot, float(mom)))
ffout = sys.argv[1]+".dat"
with open(ffout, "w") as ff:
ff.write("#lat(A) ETOT MOM\n")
with open(fout, "r") as uns:
for line in sorted(uns):
ff.write(line)
values = np.genfromtxt(fout, dtype=None, delimiter=' ', usecols=[0, 1, 2])
print(values)
输出:
[[ 2.69999400e+00 -2.54118486e+03 1.97780000e+00]
[ 2.77999500e+00 -2.54119074e+03 2.16700000e+00]
[ 2.88999500e+00 -2.54118430e+03 2.33640000e+00]
[ 2.97399600e+00 -2.54117208e+03 2.50600000e+00]
[ 2.85899600e+00 -2.54118743e+03 2.28130000e+00]
[ 2.82999200e+00 -2.54118952e+03 2.23380000e+00]
[ 2.94999300e+00 -2.54117603e+03 2.46540000e+00]
[ 2.79999300e+00 -2.54119067e+03 2.18590000e+00]
[ 2.78999600e+00 -2.54119078e+03 2.17870000e+00]
[ 2.74999600e+00 -2.54118972e+03 2.12380000e+00]
[ 2.87999300e+00 -2.54118541e+03 2.32680000e+00]]
files
中的1个文件的示例输入:
lattice constant ALAT 5.40273
16 ERR 0.183E-05 0.858E-05 EF 0.74784 -0.00000 D 14.598 M 2.2813 0.0531
ETOT -2541.18742693 SCF - cycle converged !!!!!!!!!
可以看出,我试图获取数据,但值仍然是1-d数组