为什么我在for循环的第一次迭代后得到此错误(TypeError:'_ io.TextIOWrapper'对象不可订阅)?

问题描述 投票:0回答:1

我编写的以下代码将运行一次迭代,没有任何问题。但是我希望它循环遍历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')
python h5py
1个回答
1
投票

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

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) 
© www.soinside.com 2019 - 2024. All rights reserved.