Python:从 url 读取 fortran 文件

Python: Reading fortran file from url

我想在 Python 3 中执行以下操作:读入 Fortran 文件,但从 URL 而不是本地文件。原因是对于我的具体示例,有很多文件,我想避免必须先下载它们。

我已经做到了

a) 从 URL

中读取一个简单的 .txt 文件
import urllib
from urllib.request import urlopen
url='http://www.deus-consortium.org/deus-library/filelist/deus_file_list_501.txt'
data=urllib.request.urlopen(url)
i=0
for line in data: # files are iterable
    print(i,line)
    i+=1
#alternative: data.read()

b) 像这样读入本地 FortranFile(二进制小端未格式化的 Fortran 文件):

文件来自:http://www.deus-consortium.org/deus-library/efiler1/Babel_le/boxlen648_n2048_lcdmw7/post/fof/output_00090/fof_boxlen648_n2048_lcdmw7_masst_00000

from scipy.io import FortranFile
filename='../../Downloads/fof_boxlen648_n2048_rpcdmw7_masst_00000'
ff = FortranFile(filename, 'r')
nhalos=ff.read_ints(dtype=np.int32)[0]
print('number of halos in file',nhalos)

有没有办法避免直接从 URL 下载和读取 FortranFiles?我试过了

import urllib
from urllib.request import urlopen
url='http://www.deus-consortium.org/deus-library/efiler1/Babel_le/boxlen648_n2048_lcdmw7/cube_00090/fof_boxlen648_n2048_lcdmw7_cube_00000'
pathname = urllib.request.urlopen(url)  
ff = FortranFile(pathname, 'r')
ff.read_ints()

给出"OSError: obtaining file position failed"。 pathname.read() 也不起作用,因为它是一个 fortran 文件。

有什么想法吗?提前致谢!

也许你可以使用tempfile模块来下载和读取数据?

例如:

import urllib
import tempfile
from scipy.io import FortranFile
from urllib.request import urlopen

url='http://www.deus-consortium.org/deus-library/efiler1/Babel_le/boxlen648_n2048_lcdmw7/cube_00090/fof_boxlen648_n2048_lcdmw7_cube_00000'

with tempfile.TemporaryFile() as fp:
    fp.write(urllib.request.urlopen(url).read())
    fp.seek(0)

    ff = FortranFile(fp, 'r')
    info = ff.read_ints()
    print(info)

打印:

[12808737]