abitslow
Technical User
- Apr 25, 2003
- 44
I scripted a download and unzip for .zip files. This works with no problem if the name of the .zip remains unchanged. If I try and change the name of the .zip on download then the zipfile.is_zipfile() won't recognise the file as a .zip file [though it still unzips in WinRAR].
I change the name by passing the shutil.copyfileobj() a different fdst name.
The download code used is:
The unzip code used is:
Any thoughts welcome!
Thanks.
I change the name by passing the shutil.copyfileobj() a different fdst name.
The download code used is:
Code:
import urllib.request
import shutil
import os, os.path
def mjd_downloader(url, destdir, destfilename=None):
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
#if no filename passed by destfilename, retrieve filename from ulr
if destfilename is None:
#need to isolate the file name from the url & download to it
filename = os.path.split(url)[1]
else:
#use given filename
filename = destfilename
#'Download': write the content of the downloaded file to the new file
shutil.copyfileobj(response, open(os.path.join(destdir,filename), 'wb'))
The unzip code used is:
Code:
import zipfile
from zipfile import ZipFile
import os, os.path
import shutil
def mjd_unzipper(zippathname, outfilebasename=None):
#outfilebasename is a name passed to the funtion if a new name for the content is requried
if zipfile.is_zipfile(zippathname) is True:
zfileinst = ZipFile(zippathname, 'r')
zfilepath = os.path.split(zippathname)[0]
zlen = len(zfileinst.namelist())
print("File path: ", zfilepath)
if outfilebasename is not None:
for filename in zfileinst.namelist():
memtype = os.path.splitext(filename)[1]
outfilename = os.path.join(outfilebasename + memtype)
print("Extracting: ", filename, " - to: ", outfilename)
#curzfile = zfileinst.read(filename)
curzfile = zfileinst.open(filename)
shutil.copyfileobj(curzfile, open(
os.path.join(zfilepath, outfilename), 'wb'))
else:
for i in range(zlen):
extractfile = zfileinst.namelist()[i]
memtype = os.path.splitext(extractfile)[1]
zfileinst.extract(extractfile, path = zfilepath)
zipfile.ZipFile.close(zfileinst)
else:
print("Is not a zipfile")
pass
Any thoughts welcome!
Thanks.