1

Usually, I read ascii from files with something like:

asc = rasterio.open(filepath)
array = asc.read(1)

But in some cases, all the lines of the ascii file have already been read into a variable like below:

with open(filepath) as file:
    lines = [line.upper() for line in file.readlines()]
asc_src = "".join(lines)

Is there a way to make asc from asc_source directly? I could write it to a temporary ascii file and read it back but I'd like to avoid it if possible.

1 Answer 1

3
+50

You can use a MemoryFile as described in the documentation:


from rasterio.io import MemoryFile

data = b"""\
NCOLS 16
NROWS 16
XLLCORNER 378922
YLLCORNER 4072345
CELLSIZE 30
NODATA_VALUE -9999
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5
"""

with MemoryFile(data) as memfile:
    with memfile.open() as dataset:
        print(dataset.shape)
        print(dataset.transform)

        data_array = dataset.read()
        print(data_array.dtype)


(16, 16)
| 30.00, 0.00, 378922.00|
| 0.00,-30.00, 4072825.00|
| 0.00, 0.00, 1.00|
int32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.