为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我在 for 循环的第一次迭代后收到此错误

为什么我在 for 循环的第一次迭代后收到此错误

守着一只汪 2021-11-09 20:39:19
我编写的以下代码将毫无问题地运行一次迭代。但是我希望它遍历 x 的所有值(在这种情况下有 8 个)。在它完成第一个循环后,当它进入第二个循环时,我在这一行收到一个错误 (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所以它只输出 BEAM0000 的结果(一个 .csv 文件和一个 .kml 文件)。我期待它循环并输出所有 8 个光束的两个文件。我错过了什么,为什么它不会穿过其他光束?import h5pyimport numpy as npimport csvimport simplekmlimport argparseparser = argparse.ArgumentParser(description='Creating a KML from an HD5 file')parser.add_argument('HD5file', type=str)args = parser.parse_args()HD5file = args.HD5filef = 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')
查看完整描述

1 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

当您在此处使用上下文管理器时:


with open(file, 'w') as f:

它重新分配给f,所以当您尝试访问的值等f[x],它试图调用__getitem__(x)上f,这引起了TypeError


替换此块:


with open(file, 'w') as f:

    wr = csv.writer(f)

    wr.writerows(beamlist) 

像这样:


with open(file, 'w') as fileobj:

    wr = csv.writer(fileobj)

    wr.writerows(beamlist) 


查看完整回答
反对 回复 2021-11-09
  • 1 回答
  • 0 关注
  • 215 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信