I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
However, when I run the script, I get the following error:
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (https://docs.python.org/2/library/zipfile.html#module-zipfile) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
- Get folder name
- Loop through folder and find zip files
- Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
When I use print statements, I can see that the files are in there. For example:
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
yields:
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
As I understand the documentation,
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You