The Geo-ICT Blog

Tutorials/Post – ICT, GIS, Remote Sensing, Earth System, Humanitarian, Disaster Management, Travel

Batch zipping your shapefiles with Python

In this tutorial, we are going to write a simple script to zip your shapefiles so you can upload them to Google Earth Engine (GEE). If you are following along, refer to this post, you can see that GEE takes in certain kind of files in for it to be valid shapefile. Alternatively, you can also upload a zip file that has all the supported file type inside. So we will use those file extensions to zip the shapefiles. The file extensions that will be used are:

  1. .dbf
  2. .shx
  3. .cpg
  4. .fix
  5. .prj
  6. .qix
  7. .sbn
  8. .shp
  9. .shp.xml

Use the code below to do the zipping. The inpath is your directory where you have your shapefiles and outpath is the directory where you want to write your output to. After you adjust the inpath and outpath, save the script and run as python filename.py where filename.py is the name of this script that you saved as.

import glob
import os
import re
import zipfile

file_types = ('.dbf', '.shx', '.cpg', '.fix' , '.prj', '.qix', '.sbn', '.shp', '.shp.xml')

def zip_shapes(inpath, outpath):

    files = [re.split('|'.join(file_types), f)[0] for f in os.listdir(inpath) if os.path.isfile(os.path.join(inpath, f)) and any(substring in f for substring in list(file_types))]
    files = list(set(files))
    os.chdir(inpath)
    for name in files:
        _file = name
        files_ = [f for name in [glob.glob(name + e) for e in file_types] for f in name]
        zip_path = os.path.join(outpath, _file + '.zip')
        zip = zipfile.ZipFile(zip_path, 'w', compression=zipfile.ZIP_DEFLATED)
        [zip.write(x) for x in files_]
        print('completed file: {}'.format(_file))

    print('*****************')
    print('all done')

if __name__ == '__main__':

    inpath = 'D:/input/'
    outpath = 'D:/output/'

    zip_shapes(inpath, outpath)

Previous

Converting MUTM Everest Coordinate 1830 to WGS 84 using ArcGIS: Projection and Transformation

Next

Adding and Updating attribute to a shapefile using ArcPy

1 Comment

  1. Great contents for Geo ICT enthugiast.

Leave a Reply

Powered by WordPress & Theme by Anders Norén

%d bloggers like this: