我有多个目录,每个目录都有多个文件:
Ce
+---top.txt
+---X0.0
| |
| +---Y0.0
| | |
| | +---X0.0Y0.0Z0.0.dat
| | +---X0.0Y0.0Z0.0.out
| | +---X0.0Y0.0Z0.05.dat
| | +---X0.0Y0.0Z0.05.out
| +---Y0.05
| |
| +---X0.0Y0.05Z0.0.dat
| | +---X0.0Y0.0Z0.05.out
| +---X0.0Y0.05Z0.05.dat
| +---X0.0Y0.05Z0.05.out
+---X0.05
|
+---Y0.0
| |
| +---X0.0Y0.0Z0.0.dat
| +---X0.0Y0.0Z0.0.out
| +---X0.0Y0.0Z0.05.dat
| +---X0.0Y0.0Z0.05.out
+---Y0.05
|
+---X0.0Y0.05Z0.0.dat
+---X0.0Y0.05Z0.0.out
+---X0.0Y0.05Z0.05.dat
+---X0.0Y0.05Z0.05.out
我正在尝试从“.out”文件中提取相关信息并将其写入 csv 文件。为此,我设计了以下代码:
import os
import csv
with open('results.csv', 'a', newline='') as f:
writer=csv.writer(f)
writer.writerow(['Filename', 'Optimisation Achieved?', 'Final Energy', 'Number of Defects', 'Defect Charge', 'M-L Centre X', 'M-L Centre Y', 'M-L Centre Z', 'Defect X', 'Defect Y', 'Defect Z', 'Defect Energy'])
for root, dirs, files in os.walk('.'):
for filename in files:
if filename.endswith('.out'):
file = os.path.join(root, filename)
with open(file, 'r') as reader:
opt_cnt=0
for line in reader:
s=line.strip()
if s=='**** Optimisation achieved ****':
opt_cnt+=1
if opt_cnt==1:
opt1='Y' + str(opt_cnt)
if opt_cnt==2:
opt2='Y' + str(opt_cnt)
else:
opt2='N'
elif s.startswith('Final energy='):
Final=s[18:31]
elif s.startswith('Total Number of Defects'):
Number=s[31]
elif s.startswith('Total charge on defect'):
Q=s[-4:]
elif s.startswith('Defect centre'):
centrex=s[21:28]
centrey=s[31:37]
centrez=s[40:46]
elif s.startswith('Atom/Fractional'):
coordx=s[40:49]
coordy=s[51:60]
coordz=s[62:71]
elif s.startswith('Final defect energy'):
Defect_Energy=s[-13:]
writer.writerow([filename, opt1, Final, Number, centrex, centrey, centrez, coordx, coordy, coordz, Defect_Energy])
但是,这会产生以下错误:
Traceback(最近一次通话最后):
文件“C:\Users\Rebecca\Dropbox\Brannerite\Published Potentials\interstitials\Grid\Ce\results.py”,第 39 行,在
writer.writerow([filename, opt1, Final, Number, centerx, centrey, centrez, coordx, coordy, coordz, Defect_Energy])
NameError: name 'Final' is not defined
[更改我的代码中最后一行的缩进量会更改 nameError 中出现的变量:因为代码有 16 个缩进(同样是 NameError 有 20 个缩进);将其更改为 8、12 或 24 会给出 ' NameError: name 'opt1' is not defined ]
我应该说大部分代码 [删除与 os.walk 相关的行] 已成功用于一组不同的文件(它们都在一个目录中)。
任何人都可以建议上述代码中的错误来自哪里以及如何纠正它?