I have a .fits file at a URL that I would like to read into Python as if was just on my machine. What I've tried is:
import urllib2 as url, astropy.io.fits as fits
target_url = 'https://s3.amazonaws.com/bdnyc/spex_prism_U50171_0835%2B19_chiu06.fits'
obj = url.urlopen(target_url)
dat = fits.open(obj)
But I just get IOError: File-like object does not have a 'write' method, required for mode 'ostream'.
Even if I set mode='readonly'
in fits.open()
it says it can't write to the file-like object.
Is there a way to open .fits files from a URL? Or to convert the .fits file bytes returned by urlopen()
back into an HDUList?
Based on the documentation of astropy.io.fits.open
, it has an option to read the contents of a .fits file from a URL:
cache : bool, optional
If the file name is a URL, download_file is used to open the file. This specifies whether or not to save the file locally in Astropy’s download cache (default: True).
Which means you didn't have to use urllib2
. You can just feed target_url
to fits.open
right away, as it calls astropy.utils.data.download_file
on the URL before opening it. See my code below.
In [1]: import astropy.io.fits as fits
In [2]: target_url = 'https://s3.amazonaws.com/bdnyc/spex_prism_U50171_0835%2B19_chiu06.fits'
In [3]: dat = fits.open(target_url)
In [4]: dat
Out[4]: [<astropy.io.fits.hdu.image.PrimaryHDU at 0x219a9e8>]