猿问

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

我编写的以下代码将毫无问题地运行一次迭代。但是我希望它遍历 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 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')


守着一只汪
浏览 216回答 1
1回答

繁星淼淼

当您在此处使用上下文管理器时:with open(file, 'w') as f:它重新分配给f,所以当您尝试访问的值等f[x],它试图调用__getitem__(x)上f,这引起了TypeError替换此块:with open(file, 'w') as f:&nbsp; &nbsp; wr = csv.writer(f)&nbsp; &nbsp; wr.writerows(beamlist)&nbsp;像这样:with open(file, 'w') as fileobj:&nbsp; &nbsp; wr = csv.writer(fileobj)&nbsp; &nbsp; wr.writerows(beamlist)&nbsp;
随时随地看视频慕课网APP

相关分类

Python
我要回答