[英]Why am i getting this error (TypeError: '_io.TextIOWrapper' object is not subscriptable) after the first iteration of my for loop?
The following code i wrote, will run one iteration with no problems. 我编写的以下代码将运行一次迭代而不会出现问题。 However i want it to loop through all of the values of x (which in this case there are 8).
但是我希望它循环遍历x的所有值(在这种情况下为8)。 After it does the first loop through, when it goes to the second, i get an error on this line (t = f[x]['master_int'])
完成第一个循环后,转到第二个循环,我在这条线上收到错误(t = f [x] ['master_int'])
Traceback (most recent call last):
File "Hd5_to_KML_test.py", line 16, in <module>
t = f[x]['master_int']
TypeError: '_io.TextIOWrapper' object is not subscriptable
So it only outputs results (a .csv file and a .kml file) for BEAM0000. 因此,它仅输出BEAM0000的结果(.csv文件和.kml文件)。 I was expecting it to loop through and output the two files for all 8 beams.
我期待它循环并输出所有8个光束的两个文件。 What am I missing, why won't it loop through the other beams?
我想念的是什么,为什么它不穿过其他光束呢?
import h5py
import numpy as np
import csv
import simplekml
import argparse
parser = argparse.ArgumentParser(description='Creating a KML from an HD5 file')
parser.add_argument('HD5file', type=str)
args = parser.parse_args()
HD5file = args.HD5file
f = h5py.File(HD5file, 'r')
beamlist = []
for x in f:
t = f[x]['master_int']
for i in range(0, len(t), 1000):
time = f[x]['master_int'][i]
geolat = f[x]['geolocation']['lat_ph_bin0'][i]
geolon = f[x]['geolocation']['lon_ph_bin0'][i]
beamlist.append([time, geolat, geolon])
file = x + '.csv'
with open(file, 'w') as f:
wr = csv.writer(f)
wr.writerows(beamlist)
inputfile = csv.reader(open(file, 'r'))
kml = simplekml.Kml()
for row in inputfile:
kml.newpoint(name=row[0], coords=[(row[2], row[1])])
kml.save(file + '.kml')
When you use the context manager here: 在此处使用上下文管理器时:
with open(file, 'w') as f:
it reassigns to f
, so when you try to access a value like f[x]
, it tries to call __getitem__(x)
on f
, which raises a TypeError
它重新分配给
f
,所以当您尝试访问类似f[x]
的值时,它将尝试在f
上调用__getitem__(x)
,这会引发TypeError
replace this block: 替换此块:
with open(file, 'w') as f:
wr = csv.writer(f)
wr.writerows(beamlist)
with something like: 与类似:
with open(file, 'w') as fileobj:
wr = csv.writer(fileobj)
wr.writerows(beamlist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.