Because recently, the step of batch vector clipping grid has always been used , Or write a blog to record , In case you can't find the code , This code is also what I found on the Internet .
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Created on Fri Jan 8 16:31:59 2021 """
import os
# Corresponding to oneself python Package installation address , It's also prj.db Where documents are stored , Search directly on the computer , choice osgeo The path of the folder is OK , I thought I was confused and pretended a lot gdal Well , then prj.db Too many documents , The code can't find any , So here I add a line of code to point out my Prj.bd Where does the file exist .
os.environ['PROJ_LIB'] = r'E:\Users\Lib\site-packages\osgeo\data\proj'
import time,os
from osgeo import gdal
import numba
@numba.jit # Program acceleration
def clip_batch(in_folder, out_folder, in_shape):
files = os.listdir(in_folder)
for file in files:
if file[-4:] == '.tif':
filename = os.path.join(in_folder,file)
in_raster = gdal.Open(filename)
out_raster = os.path.join(out_folder,file)
ds = gdal.Warp(out_raster,in_raster,format = 'GTiff',
cutlineDSName = in_shape,
cropToCutline = True,
creationOptions=["TILED=YES", "COMPRESS=LZW"],
cutlineWhere = None, dstNodata = -999)
ds=None
if __name__=="__main__":
start = time.perf_counter() # Starting time
in_shape = r"E:\backup_1\small_area.shp" # Vector range
in_folder = r"E:\backup_1" # Enter the grid path
#out_folder=r"E:\caijian" # Output grid path
out_folder=r"E:\backup_1\caijian2" # Output grid path
clip_batch(in_folder, out_folder, in_shape)
end = time.perf_counter() # End time
print('finish')
print('Running time: %s Seconds'%(end-start))