Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Programming ArcGIS 10.1 with Python Cookbook

You're reading from   Programming ArcGIS 10.1 with Python Cookbook This book provides the recipes you need to use Python with AcrGIS for more effective geoprocessing. Shortcuts, scripts, tools, and customizations put you in the driving seat and can dramatically speed up your workflow.

Arrow left icon
Product type Paperback
Published in Feb 2013
Publisher Packt
ISBN-13 9781849694445
Length 304 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Eric Pimpler Eric Pimpler
Author Profile Icon Eric Pimpler
Eric Pimpler
Arrow right icon
View More author details
Toc

Table of Contents (21) Chapters Close

Programming ArcGIS 10.1 with Python Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Fundamentals of the Python Language for ArcGIS 2. Writing Basic Geoprocessing Scripts with ArcPy FREE CHAPTER 3. Managing Map Documents and Layers 4. Finding and Fixing Broken Data Links 5. Automating Map Production and Printing 6. Executing Geoprocessing Tools from Scripts 7. Creating Custom Geoprocessing Tools 8. Querying and Selecting Data 9. Using the ArcPy Data Access Module to Select, Insert, and Update Geographic Data and Tables 10. Listing and Describing GIS Data 11. Customizing the ArcGIS Interface with Add-Ins 12. Error Handling and Troubleshooting Automating Python Scripts Five Things Every GIS Programmer Should Know How to Do with Python Index

Creating ZIP files


GIS often requires the use of large files that will be compressed into a .zip format for ease of sharing. Python includes a module that you can use to decompress and compress files in this format.

Getting ready

Zip is a common compression and archive format and is implemented in Python through the zipfile module. The ZipFile class can be used to create, read, and write .zip files. To create a new .zip file, simply provide the filename along with a mode such as w, which indicates that you want to write data to the file. In the following code example, we are creating a .zip file called datafile.zip. The second parameter, w, indicates that a new file will be created. A new file will be created or an existing file with the same name will be truncated in the write mode. An optional compression parameter can also be used when creating the file. This value can be set to either ZIP_STORED or ZIP_DEFLATED:

zipfile.ZipFile('dataFile.zip', 'w',zipfile.ZIP_STORED)

In this exercise, you will use Python to create file, add files, and apply compression to a .zip. You'll be archiving all the shapefiles located in the c:\ArcpyBook\data directory.

How to do it…

Follow these steps to learn how to create a script that build a .zip file:

  1. Open IDLE and create a script called c:\ArcpyBook\Appendix2\CreateZipfile.py.

  2. Import the zipfile and os modules:

    import os
    import zipfile
  3. Create a new .zip file called shapefiles.zip in write mode and add a compression parameter:

    zfile = zipfile.ZipFile("shapefiles.zip", "w", zipfile.ZIP_STORED)
  4. Next, we'll use the os.listdir() function to create a list of files in the data directory:

    files = os.listdir("c:/ArcpyBook/data")
  5. Loop through a list of all the files and write to the .zip file, if the file ends with shp, dbf, or shx:

    for f in files:
      if f.endswith("shp") or f.endswith("dbf") or f.endswith("shx"):
        zfile.write("C:/ArcpyBook/data/" + f)
  6. Print out a list of all the files that were added to the zip archive. You can use the ZipFile.namelist() function to create a list of files in the archive:

    for f in zfile.namelist():
        print "Added %s" % f
  7. Close the .zip archive:

    zfile.close()
  8. The entire script should appear as follows:

    import os
    import zipfile
    
    #create the zip file
    zfile = zipfile.ZipFile("shapefiles.zip", "w", zipfile.ZIP_STORED)
    files = os.listdir("c:/ArcpyBook/data")
    
    for f in files:
      if f.endswith("shp") or f.endswith("dbf") or f.endswith("shx"):
        zfile.write("C:/ArcpyBook/data/" + f)
    
    #list files in the archive
    for f in zfile.namelist():
        print "Added %s" % f
    
    zfile.close()
  9. Save and run the script. You should see the following output:

    Added ArcpyBook/data/Burglaries_2009.dbf
    Added ArcpyBook/data/Burglaries_2009.shp
    Added ArcpyBook/data/Burglaries_2009.shx
    Added ArcpyBook/data/Streams.dbf
    Added ArcpyBook/data/Streams.shp
    Added ArcpyBook/data/Streams.shx
    
  10. In Windows Explorer, you should be able to see the output .zip file as shown in the following screenshot. Note the size of the archive. This file was created without compression:

  11. Now, we're going to create a compressed version of the .zip file to see the difference. Make the following changes to the line of code that creates the .zip file:

    zfile = zipfile.ZipFile("shapefiles2.zip", "w", zipfile.ZIP_DEFLATED)
  12. Save and re-run the script.

  13. Take a look at the size of the new shapefiles2.zip file that you just created. Note the decreased size of the file due to compression:

How it works…

In this recipe, you created a new .zip file called shapefiles.zip in write mode. In the first iteration of this script, you didn't compress the contents of the file. However, in the second iteration, you did by using the DEFLATED parameter passed into the constructor for the ZipFile object. The script then obtained a list of files in the data directory and looped through each of the files. Each file that has an extension of .shp, .dbf, or .shx is then written to the archive file using the write() function. Finally, the names of each of the files written to the archive is printed to the screen.

There's more…

The contents of an existing file stored in a ZIP archive can be read using the read() method. The file should first be opened in a read mode, and then you can call the read() method passing in a parameter that represents the filename that should be read. The contents of the file can then be printed to the screen, written to another file, or stored as a list or dictionary variable.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image