Why am i getting this error (TypeError: '_io.TextIOWrapper' object is not subscriptable) after the first iteration of my for loop?

Why am i getting this error (TypeError: '_io.TextIOWrapper' object is not subscriptable) after the first iteration of my for loop?

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

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

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

它重新分配给 f,因此当您尝试访问像 f[x] 这样的值时,它会尝试在 f 上调用 __getitem__(x),这会引发 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)