内存文件

本文档的其他部分解释了Rasterio如何访问存储在由其他程序编写的磁盘上现有文件中的数据,或写入其他GIS程序使用的文件。文件名是典型的输入,磁盘上的文件是典型的输出。

with rasterio.open('example.tif') as dataset:
    data_array = dataset.read()

对于具有字节流的python程序,有不同的选项,例如,从网络套接字,作为其输入或输出而不是文件名。一种是使用磁盘上的临时文件。

import tempfile


with tempfile.NamedTemporaryFile() as tmpfile:
    tmpfile.write(data)
    with rasterio.open(tmpfile.name) as dataset:
        data_array = dataset.read()

另一个是栅格的 MemoryFile 是gdal内存文件系统中对象的抽象。

内存文件:Bytesio满足NamedTemporaryFile

这个 MemoryFile 类的行为有点像 BytesIONamedTemporaryFile . 一个geotiff文件,按顺序 data 字节可以在内存中打开,如下所示。

from rasterio.io import MemoryFile


 with MemoryFile(data) as memfile:
     with memfile.open() as dataset:
         data_array = dataset.read()

此代码可能比使用 NamedTemporaryFile 大约是记忆中价格的两倍。

写备忘录

对空的增量写入 MemoryFile 也有可能。

with MemoryFile() as memfile:
    while True:
        data = f.read(8192)  # ``f`` is an input stream.
        if not data:
            break
        memfile.write(data)
    with memfile.open() as dataset:
        data_array = dataset.read()

这两种模式不兼容:a MemoryFile 无法扩展用字节序列初始化的。

空的 MemoryFile 也可以使用数据集API方法写入。

with MemoryFile() as memfile:
    with memfile.open(driver='GTiff', count=3, ...) as dataset:
        dataset.write(data_array)

读取内存文件

喜欢 BytesIO, MemoryFile implements the Python file protocol and provides read(), seek(), and tell() methods. Instances are thus suitable as arguments for methods like requests.post() .

with MemoryFile() as memfile:
    with memfile.open(driver='GTiff', count=3, ...) as dataset:
        dataset.write(data_array)

     requests.post('https://example.com/upload', data=memfile)