Python:从 url 读取 fortran 文件



我想在Python 3中执行以下操作:在FortranFile中读取,但从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:获取文件位置失败"。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]

最新更新