本文整理汇总了Python中zipfile.ZipFile.extractall方法的典型用法代码示例。如果您正苦于以下问题:Python ZipFile.extractall方法的具体用法?Python ZipFile.extractall怎么用?Python ZipFile.extractall使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zipfile.ZipFile
的用法示例。
在下文中一共展示了ZipFile.extractall方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: download_demo
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def download_demo(demo_name):
"Downloads and extracts the demo zip file"
print(green("- Downloading"), end="")
response = urllib2.urlopen(DEMOS[demo_name]["url"])
# Extract real name of zipfile
content_disposition = response.headers.getheader("content-disposition")
real_name = os.path.splitext(content_disposition.split("; ")[1].split("=")[1])[0]
fname = "{0}.zip".format(demo_name)
# Download zipfile
with open(fname, "wb") as tmpfile:
while True:
packet = response.read(2 ** 16)
if not packet:
print(green("done"))
break
tmpfile.write(packet)
sys.stdout.write(green("."))
sys.stdout.flush()
response.close()
print(green("- Extracting"))
# Extract zipfile
zipfile = ZipFile(fname)
zipfile.extractall()
# Clean up and rename to the correct demo name
os.remove(fname)
os.rename(real_name, demo_name)
示例2: build
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def build(worker_dir, sha, repo_url, destination, concurrency):
"""Download and build sources in a temporary directory then move exe to destination"""
tmp_dir = tempfile.mkdtemp()
os.chdir(tmp_dir)
with open('sf.gz', 'wb+') as f:
f.write(requests.get(github_api(repo_url) + '/zipball/' + sha).content)
zip_file = ZipFile('sf.gz')
zip_file.extractall()
zip_file.close()
for name in zip_file.namelist():
if name.endswith('/src/'):
src_dir = name
os.chdir(src_dir)
custom_make = os.path.join(worker_dir, 'custom_make.txt')
if os.path.exists(custom_make):
with open(custom_make, 'r') as m:
make_cmd = m.read().strip()
subprocess.check_call(make_cmd, shell=True)
else:
subprocess.check_call(MAKE_CMD + ' -j %s' % (concurrency), shell=True)
shutil.move('stockfish'+ EXE_SUFFIX, destination)
os.chdir(worker_dir)
shutil.rmtree(tmp_dir)
示例3: getWP
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def getWP():
print 'downloading wordpress........'
open(cwd + '/temp/wp.zip', 'wb').write(urllib.urlopen('http://fr.wordpress.org/wordpress-3.5-fr_FR.zip').read())
zip = ZipFile(cwd + '/temp/wp.zip')
print 'done'
print 'Extracting wordpress...'
zip.extractall(cwd + '/temp/')
print 'done'
print 'Moving the wordpress installation to C:/wamp/www/' + projectName
# - Copy the WP installation
shutil.copytree(cwd+ '/temp/wordpress/', wampPath + projectName)
# - remove the junk
#copytree(cwd + '/temp/wordpress/', wampPath + projectName)
print 'done'
print 'Getting ready for the first run.. Opening your web browser...'
new = 2 # open in a new tab, if possible
# open a public URL, in this case, the webbrowser docs
url = "localhost/" + projectName + "/wp-admin/setup-config.php"
webbrowser.open(url,new=new)
示例4: _prepare
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def _prepare():
""" Create two dirs, one with one dataset and one with two datasets
"""
need_internet()
global _prepared
if _prepared and os.path.isfile(_prepared[2]):
return _prepared
# Prepare sources
fname1 = get_remote_file('images/dicom_sample1.zip')
fname2 = get_remote_file('images/dicom_sample2.zip')
dname1 = os.path.join(test_dir, 'dicom_sample1')
dname2 = os.path.join(test_dir, 'dicom_sample2')
# Extract zipfiles
z = ZipFile(fname1)
z.extractall(dname1)
z.extractall(dname2)
z = ZipFile(fname2)
z.extractall(dname2)
# Get arbitrary file names
fname1 = os.path.join(dname1, os.listdir(dname1)[0])
fname2 = os.path.join(dname2, os.listdir(dname2)[0])
# Cache and return
_prepared = dname1, dname2, fname1, fname2
return dname1, dname2, fname1, fname2
示例5: parse_template
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def parse_template(template_name):
"""Resolve template name into absolute path to the template
and boolean if absolute path is temporary directory.
"""
if template_name.startswith('http'):
if '#' in template_name:
url, subpath = template_name.rsplit('#', 1)
else:
url = template_name
subpath = ''
with tempfile.NamedTemporaryFile() as tmpfile:
urlretrieve(url, tmpfile.name)
if not is_zipfile(tmpfile.name):
raise ConfigurationError("Not a zip file: %s" % tmpfile)
zf = ZipFile(tmpfile)
try:
path = tempfile.mkdtemp()
zf.extractall(path)
return os.path.join(path, subpath), True
finally:
zf.close()
registry = TemplatesRegistry()
if registry.has_template(template_name):
path = registry.path_of_template(template_name)
elif ':' in template_name:
path = resolve_dotted_path(template_name)
else:
path = os.path.realpath(template_name)
if not os.path.isdir(path):
raise ConfigurationError('Template directory does not exist: %s' % path)
return path, False
示例6: update
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def update(self, update):
dpath = self.xplanedir + '/Resources/Downloads'
installpath = self.xplanedir + '/Resources/plugins/PythonScripts'
# Broadcast message to all plugins
XPLMSendMessageToPlugin(XPLM_NO_PLUGIN_ID, 0x8000000 | 8090 , long(1))
PI_SendMessageToScript(self, None, 0x8000000 | 8090, 1)
sleep(1)
if not os.path.exists(dpath):
os.mkdir(dpath)
if update['update_type'] == 'direct' and update['update_filename']:
urllib.urlretrieve(update['update_url'], dpath + '/' + update['update_filename'])
copy(dpath + '/' + update['update_filename'], installpath + '/' + update['update_filename'])
print dpath + '/' + update['update_filename'], installpath + '/' + update['update_filename']
elif update['update_type'] == 'zip':
zipfile = dpath + '/._xpjpcUPDATE.zip'
# Download update
urllib.urlretrieve(update['update_url'], zipfile)
zip = ZipFile(zipfile, 'r')
# Check zip file
if not zip.testzip():
# Unzip
unzipdir = dpath + '/' + zip.namelist()[0]
zip.extractall(dpath)
zip.close()
# Move files
self.tcopy(unzipdir, installpath)
rmtree(unzipdir)
os.remove(zipfile)
示例7: _download_xbrl_file
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def _download_xbrl_file(info_dicts,p):
no = p
directory_path = os.getcwd()+'/xbrl_files/'
while(no < len(info_dicts)):
info_dict = info_dicts[no]
no += proc
# 証券CDごとのディレクトリ作成
company_path = directory_path + info_dict['cd'] + '/'
ir_path = company_path + info_dict['id']
make_directory(company_path)
# 証券コード×IR情報ごとのディレクトリ作成
if os.path.exists(ir_path):
continue
make_directory(ir_path)
print('Process('+str(p + 1) + '):downloading:' + info_dict['update']+'_'+info_dict['title'])
url = info_dict['url']
r = requests.get(url)
if r.ok:
#Requestによりファイルを取得して、Unzipする
r = requests.get(url)
z = ZipFile(io.BytesIO(r.content))
z.extractall(ir_path) # unzip the file and save files to path.
示例8: unzip_snap_mp4
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def unzip_snap_mp4(abspath, quiet=False):
zipped_snap = ZipFile(abspath)
# unzip /path/to/zipfile.mp4 to /path/to/zipfile
unzip_dir = os.path.splitext(abspath)[0]
zipped_snap.extractall(unzip_dir)
# move /path/to/zipfile.mp4 to /path/to/zipfile.zip
os.rename(abspath, unzip_dir + '.zip')
for f in os.listdir(unzip_dir):
# mv /path/to/zipfile/media~* /path/to/zipfile.mp4
if f.split('~')[0] == 'media':
os.rename(os.path.join(unzip_dir, f), unzip_dir + '.mp4')
# mv /path/to/zipfile/overlay~* /path/to/zipfile_overlay.png
elif f.split('~')[0] == 'overlay':
os.rename(os.path.join(unzip_dir, f),
unzip_dir + '_overlay.png')
try:
os.rmdir(unzip_dir)
except OSError:
print('Something other than a video or overlay was in {0}. \
Cannot remove directory, not empty.'
.format(unzip_dir + '.zip'))
if not quiet:
print('Unzipped {0}'.format(abspath))
示例9: load
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def load(self):
"""Creates one Temporary Document and write data into it.
Return the url for the document.
"""
# creates only the url of the file.
file_path = tempfile.NamedTemporaryFile(suffix=".%s" % self.source_format,
dir=self.directory_name).name
# stores the data in temporary file
open(file_path, 'wb').write(self.original_data)
# If is a zipfile is need extract all files from whitin the compressed file
if is_zipfile(file_path):
zipfile = ZipFile(file_path)
zip_filename_list = zipfile.namelist()
if 'mimetype' not in zip_filename_list and \
'[Content_Types].xml' not in zip_filename_list:
zipfile_path = file_path
zipfile.extractall(path=self.directory_name)
zipfile.close()
filename_list = listdir(self.directory_name)
if 'index.html' in filename_list:
file_path = join(self.directory_name, 'index.html')
else:
mimetype_list = ['text/html', 'application/xhtml+xml']
for filename in filename_list:
if mimetypes.guess_type(filename)[0] in mimetype_list:
file_path = join(self.directory_name, filename)
break
if zipfile_path != file_path:
remove(zipfile_path)
return file_path
示例10: archive_download
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def archive_download(self, url, cache_path, checksum):
rc = 0
# Download
arcfile = os.path.join(cache_path, os.path.basename(url))
tdir = os.path.dirname(arcfile)
filetool.directory(tdir)
tfp = open(arcfile, "wb")
#(fname, urlinfo) = urllib.urlretrieve(url, arcfile)
urlobj = urllib.urlopen(url)
assert urlobj.getcode() == 200, "Could not the download contrib archive: %s" % url
hashobj = self.copy_and_hash(urlobj.fp, tfp)
assert hashobj.hexdigest()==checksum, "Checksum of archive does not validate (should be: %s): %s" % (checksum, arcfile)
urlobj.close()
tfp.close()
# Extract
if url.endswith('.zip'):
zipf = ZipFile(arcfile, 'r')
zipf.extractall(tdir)
zipf.close()
else: # .tar, .tgz, .tar.gz, .tar.bz2
tar = tarfile.open(arcfile)
tar.extractall(tdir)
tar.close
# Eliminate archive top-dir
_, archive_dirs, _ = os.walk(tdir).next()
assert archive_dirs, "The downloaded archive is not in single top-dir format: %s" % arcfile
archive_top = os.path.join(tdir, archive_dirs[0]) # just take the first dir entry
for item in os.listdir(archive_top):
shutil.move(os.path.join(archive_top, item), tdir)
os.rmdir(archive_top)
os.unlink(arcfile)
return rc
示例11: download_and_unzip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def download_and_unzip(url, pth='./'):
if not os.path.exists(pth):
print('Creating the directory: {}'.format(pth))
os.makedirs(pth)
print('Attempting to download the file: ', url)
file_name = os.path.join(pth, url.split('/')[-1])
try:
f, header = urlretrieve(url, file_name)
except:
msg = 'Cannot download file: {}'.format(url)
raise Exception(msg)
# Unzip the file, and delete zip file if successful.
if 'zip' in os.path.basename(file_name) or 'exe' in os.path.basename(file_name):
z = ZipFile(file_name)
try:
print('Extracting the zipfile...')
z.extractall(pth)
except:
p = 'Could not unzip the file. Stopping.'
raise Exception(p)
z.close()
elif 'tar' in os.path.basename(file_name):
ar = tarfile.open(file_name)
ar.extractall(path=pth)
ar.close()
print('Deleting the zipfile...')
os.remove(file_name)
print('Done downloading and extracting...')
示例12: main
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def main(args):
manifest = args[1]
print("creating work directory")
workdir = tempfile.mkdtemp(prefix="work-dir", dir=".")
print("extracting manifest")
zip_file = ZipFile(manifest, "r")
zip_file.extractall(workdir)
zip_file = ZipFile(os.path.join(workdir, "consumer_export.zip"), "r")
zip_file.extractall(workdir)
print("reading products")
products = glob.glob(os.path.join(workdir, "export", "products",
"*.json"))
content = []
for product in products:
print product
content.extend(load_content(product))
# These credentials should be good for a normal Katello/SAM deployment:
conn = psycopg2.connect("dbname=canadianTenPin user=postgres")
scan_content(conn, content)
conn.commit()
print("cleaning up")
shutil.rmtree(workdir)
print("all done.")
示例13: acs
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def acs(file_num, geo_type_dir):
base_url = 'http://www2.census.gov/acs2010_5yr/summaryfile/2006-2010_ACSSF_By_State_By_Sequence_Table_Subset/'
path = os.path.join(
state_name.replace(' ', ''), geo_type_dir,
'20105%s%04d000.zip' % (state_abbr, file_num)
)
reader = remote_fallback_reader(
'../data/acs2006_2010_5yr/summaryfile/2006-2010_ACSSF_By_State_By_Sequence_Table_Subset',
base_url,
path
)
z = ZipFile(reader)
n = z.namelist()
z.extractall('/tmp/')
files = ['e20105%s%04d000.txt' % (state_abbr, file_num),
'm20105%s%04d000.txt' % (state_abbr, file_num),]
for f in files:
z.extract(f, '/tmp/')
# count the number of columns, to determine how many columns to fill
firstline = open('/tmp/' + f).readline()
if not firstline:
# some files are empty, so just continue to the next
os.unlink('/tmp/' + f)
continue
cols = ['fileid', 'filetype', 'stusab', 'chariter', 'cifsn', 'logrecno']
cols.extend(map(
lambda c: 'col%s' % str(c+1),
range(firstline.count(',')+1-6) # subtract 6 to account for the 6 geo header columns
))
cursor.copy_from(open('/tmp/%s' % f), 'census_row', sep=',',
columns=cols)
os.unlink('/tmp/' + f)
示例14: ImportTfZip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def ImportTfZip( config = None, ConfigSet = "ImportTfZip" ):
'''
Imports events and config from file (or stdin)
@param config: The config object to use. If None, then we try to use defaults or stdin
@param ConfigSet: The section of the configuration to use
@raise KeyError: If supplied ConfigSet is not in config
@return: (weeksums, config)
'''
# fetch config values
ZipDataDir = config.get( ConfigSet, "ZipDataDir" ).rstrip("/\\")
ZipFilename = config.get( ConfigSet, "ZipFile" )
zf = ZipFile( ZipFilename )
zf.extractall( ZipDataDir )
ImportTfSection = "ImportTf"
SheetName = config.get( ImportTfSection, "Sheetname" )
AllEvents = []
for DataFile in zf.namelist():
config.set( ImportTfSection, "InFile", "%s/%s"%(ZipDataDir, DataFile) )
config.set( ImportTfSection, "CsvFile", "%s/%s.%s.%s"%(ZipDataDir, DataFile,SheetName,u'csv') )
m = re.findall( "[0-9]{4}", DataFile )
if m:
config.set( ImportTfSection, "Year", m[0] )
try:
events, config = ImportTf( config, ImportTfSection )
AllEvents += events
except ValueError, e :
# no events
sys.stderr.write( "%s\n"% e.message )
示例15: _dl_ui
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import extractall [as 别名]
def _dl_ui():
url = urlopen(self._dist_url)
z = ZipFile(StringIO(url.read()))
names = [i for i in z.namelist() if '.DS_exStore' not in i and '__MACOSX' not in i]
z.extractall(self.update_dir, members=names)
log.info("Downloaded files for UI commit " + str(self.git_version).replace("\n", ""))
return self.branch