使用astropy.io读取一堆FITS时出现OSError 24(打开的文件太多)

Arc*_*s B 5 python fits astropy

我正在尝试使用astropy.io.fits以下方式将一些2000 FITS加载到内存中:

def readfits(filename):
    with fits.open(filename) as ft:
        # the fits contain a single HDU
        data = ft[0].data
    return data

data_sci = []
for i in range(2000):
    data_sci.append(readfits("filename_{}.fits".format(i)))
Run Code Online (Sandbox Code Playgroud)

但是,到达1015th文件时,OSError: [Errno 24] Too many open files将引发。

我有同样的问题:

def readfits(filename):
    ft = fits.open(filename) as ft:
    data = ft[0].data
    ft.close()
    return data
Run Code Online (Sandbox Code Playgroud)

我怀疑astropy.io.fits无法正确关闭文件。有什么办法可以强制关闭文件?

Igu*_*aut 3

您的readfits函数实际上使文件句柄保持打开状态,以便保持对数据的访问,因为默认情况下它会创建数据的mmap并且不会将其完全读入物理内存,如下所述:http ://astropy.readthedocs.org/ en/latest/io/fits/appendix/faq.html#im-opening-many-fits-files-in-a-loop-and-getting-oserror-too-many-open-files

顺便说一句,如果您只想要一个从第一个 HDU 中读取数据的函数,则该函数已经内置: http: //docs.astropy.org/en/v1.0.5/io/fits/api/files.html#astropy .io.fits.getdata

没有必要重新发明轮子。