1

Python beginner here. I am using python to reproject a folder of rasters (.tifs). Each raster has a projection that I want to change to WGS 1984 (espg:4326). I want to use an open-source GIS library rather than ESRI's ArcPy library. I'm assuming this needs to occur with a loop going through my folder directory and reprojecting each raster one by one.

My current lines of code read:

newpath = 'path to my folder' 
for raster in os.listdir(newpath):
    gdal.Warp(new_filename, raster, dstSRS="+init=epsg:4326")

The problem I'm attempting to solve is how to correctly specify the output filename of each raster in the gdal.Warp line.

Any suggestions?

2 Answers 2

2

If you need to save the reprojected raster in the same dir and call it /path/to/newpath/raster_reproj.tif:

newpath = 'path to my folder' 
for raster in os.listdir(newpath):
    basename, extension = os.path.splitext(raster)
    old_raster = os.path.join(newpath, raster)
    new_raster = os.path.join(newpath, f"{basename}_reproj{extension}")
    gdal.Warp(new_raster, old_raster, dstSRS="+init=epsg:4326")

If you need to save the reprojected raster in a different dir and leave the filename the same:

oldpath = 'path to my folder with data' 
newpath = 'path to my folder to write reprojected to' 
for raster in os.listdir(oldpath):
    old_raster = os.path.join(oldpath, raster)
    new_raster = os.path.join(newpath, raster)
    gdal.Warp(new_raster, old_raster, dstSRS="+init=epsg:4326")
0
1

Clearly a Python question, not really GIS related

from pathlib import Path

newpath = "tif/input/dir/"
destination_dir = "/else/where/dir/"
for raster in Path(newpath).glob('*.tif'):
    dest_file = Path(destination_dir).joinpath(f"{raster.stem}_4326.tif")
    gdal.Warp(f"{dest_file}", f"{raster}", dstSRS="+init=epsg:4326")

See https://pymotw.com/3/pathlib/ or https://realpython.com/python-pathlib/ among other pathlib tutorials (os module approach can be used but is not recommended nowadays)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.