[Python] How can I check if `src` and `dst` are the same when writing with `rasterio.open()`

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I want to read a geotiff, reproject, and write to a new geotiff based on the code from the rasterio docs (https://rasterio.readthedocs.io/en/stable/topics/reproject.html) (the actual transformation is of course more complex than shown below).

    There are a few potential problems that I need to deal with:

    1. The output file might already exist; in this case I want to overwrite it

    try:
    os.remove(fname)
    except FileNotFoundError:
    pass

    1. The output file might be opened in another program. Ideally I would like to overwrite it regardless but I understand this is difficult/impossible to do, therefore I catch this as a PermissionError:

    try:
    write_reprojected(...)
    except (PermissionError, OSError):
    print("output_file is opened elsewhere, close and try again")


    3. However, if the input and output files are accidently specified to be the same I would like a different behaviour of the program. I am trying to catch this with

    if os.path.abspath(src.files[0]) == os.path.abspath(fname):
    #raise MyCustomException()
    print("Trying to write file to its old location")


    but I'm not sure if the string comparison is the best way.

    Question: Is there a better way to check if src and dst are the same when writing with rasterio.open()? And also, is there a way to remove/overwrite a file that is used by a different program?


    import os
    import numpy as np
    import rasterio
    from rasterio.warp import calculate_default_transform, reproject, Resampling

    def write_reprojected(src, crs, transform, width, height, fname):

    # raise Exception if file is open for reading
    if os.path.abspath(src.files[0]) == os.path.abspath(fname):
    #raise MyCustomException()
    print("Trying to write file to its old location")

    kwargs = src.meta.copy()
    kwargs.update({
    'crs': crs,
    'transform': transform,
    'width': width,
    'height': height})

    # overwrite file if it already exists
    try:
    os.remove(fname)
    except FileNotFoundError:
    pass

    with rasterio.open(fname, 'w', **kwargs) as dst:
    for i in range(1, src.count + 1):
    reproject(
    source=rasterio.band(src, i),
    destination=rasterio.band(dst, i),
    src_transform=src.transform,
    src_crs=src.crs,
    dst_transform=transform,
    dst_crs=crs,
    resampling=Resampling.bilinear)


    input_file = 'old_folder\old_file.tif'

    output_folder = 'new_folder'
    output_file = 'new_file.tif'
    try:
    os.makedirs(new_folder)
    except FileExistsError:
    pass

    with rasterio.open(input_file, 'r') as src:
    transform, width, height = aligned_target(
    src.transform, src.width, src.height, [round(r) for r in src.res])
    try:
    write_reprojected(src, src.crs, transform, width, height,
    os.path.join(output_folder, output_file))
    except (PermissionError, OSError):
    print("output_file is opened elsewhere, close and try again")

    Continue reading...

Compartilhe esta Página