Skip to content

Instantly share code, notes, and snippets.

@shimo164
Last active June 15, 2019 04:21
Show Gist options
  • Select an option

  • Save shimo164/7f61cc38ca166167f32d9218adfc5e58 to your computer and use it in GitHub Desktop.

Select an option

Save shimo164/7f61cc38ca166167f32d9218adfc5e58 to your computer and use it in GitHub Desktop.
'''
Extract a file in a zip file, without opening the zip file
Parameters-------
file_to_get:
filename like 'test.txt' to get
zip_file:
target zip filename like 'zipfile.zip'
zip_dir:
directory path where zip file is.
If zip and python code file are in same directory, '.'.
save_dir = '.'
directory to save exctract file.
If same directory, '.'.
'''
import glob
import sys
import zipfile
file_to_get = 'test.txt'
zip_file = 'zipfile.zip'
zip_dir = '.'
save_dir = '.'
def extract_file_from_zip(file_to_get, zip_file, zip_dir, save_dir):
zip_path = zip_dir+'/'+zip_file
with zipfile.ZipFile(zip_path, 'r') as myzip:
for n in myzip.namelist():
if file_to_get in n:
myzip.extract(n, save_dir)
print('extracted:', n)
sys.exit()
print(zip_file, ': not found')
if __name__ == "__main__":
extract_file_from_zip(file_to_get, zip_file, zip_dir, save_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment