Reprojecting each tif located in Folder Directory using GDAL in Python

coordinate systemfor loopgdalgdalwarpgeotiff-tiff

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?

Best Answer

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")