I have 5000 Zip archives that contains a json file with an information (versionName),
I want to rename those zip files, the best way I found to do that in python is
to read the jsons and get the information I need, then rename each zip like that : "Archive_name.zip => Archive_name_versionName.zip"
Here is my python code :
import zipfile
archive = zipfile.ZipFile('/home/AndroidBags/aasuited.net.word.zip', 'r')
print(archive)
jsonre = archive.read('meta_google_play/apk_aasuited.net.word.json')
print(jsonre)
Here the result of that script :
{"appdata":
[{"versionName": "1.24.1", "size": 19480447}]}
How can I acces the versionName value and rename the zip file in python ? Thank you
import os
import json
version_name = json.loads(jsonre)['appdata'][0]['versionName']
os.rename(
'/home/AndroidBags/aasuited.net.word.zip',
'./aasuited.net.word.' + version_name + '.zip'
)
This also moves the zip file to the current work directory.
Related
I am trying to zip a single file in python. For whatever reason, I'm having a hard time getting down the syntax. What I am trying to do is keep the original file and create a new zipped file of the original (like what a Mac or Windows would do if you archive a file).
Here is what I have so far:
import zipfile
myfilepath = '/tmp/%s' % self.file_name
myzippath = myfilepath.replace('.xml', '.zip')
zipfile.ZipFile(myzippath, 'w').write(open(myfilepath).read()) # does not zip the file properly
The correct way to zip file is:
zipfile.ZipFile('hello.zip', mode='w').write("hello.csv")
# assume your xxx.py under the same dir with hello.csv
The python official doc says:
ZipFile.write(filename, arcname=None, compress_type=None)
Write the file named filename to the archive, giving it the archive name arcname
You pass open(filename).read() into write(). open(filename).read() is a single string that contains the whole content of file filename, it would throw FileNotFoundError because it is trying to find a file named with the string content.
If the file to be zipped (filename) is in a different directory called pathname, you should use the arcname parameter. Otherwise, it will recreate the full folder hierarchy to the file folder.
from zipfile import ZipFile
import os
with ZipFile(zip_file, 'w') as zipf:
zipf.write(os.path.join(pathname,filename), arcname=filename)
Try calling zipfile.close() afterwards?
from zipfile import ZipFile
zipf = ZipFile("main.zip","w", zipfile.ZIP_DEFLATED)
zipf.write("main.json")
zipf.close()
Since you also want to specify the directory try using os.chdir:
#!/usr/bin/python
from zipfile import ZipFile
import os
os.chdir('/path/of/target/and/destination')
ZipFile('archive.zip', 'w').write('original_file.txt')
Python zipfile : Work with Zip archives
Python Miscellaneous operating system interfaces
I wannted to extract some selected files from a sample.tar.gz files ( do not need to be extracted all the files inside sample.tar.gz files ) the file structures are looks like below.
sample.tar.gz is the base file, under this base file following files are contained.
hello_usb.tar.gz
hello_usb1.tar.gz
hello_usb2.tar.gz
world_usb1.tar.gz
world_usb2.tar.gz
world_usb3.tar.gz
I wanted to extract only "hello_*" files are to be extracted ( while extracting it should create a fiolder name same as the file name for example, while extracting hello_usb.tar.gz file it should create a folder name called as hello_usb.tar.gz/... )
I have tried with following codes but no luck.
tar = tarfile.open("D:\Python34\Testing\sample.tar.gz", "r:gz")
only_names = tar.getnames()
for count in range(len(only_names)):
print (only_names[count][:9])
if only_names[count][:9] == "hello_usb":
tar.extract(only_names[count], path = "D:\Python34\Testing")
#tar.extractfile(only_names[count])
Your help would be highly appreciated
Something like this may work.
import shutil
import glob
import os
with tarfile.open('D:\Python34\Testing\sample.tar.gz', 'r:gz') as tar:
tar.extractall()
os.chdir('sample')
for arch in glob.glob('hello_*'):
shutil.unpack_archive(arch, 'D:\Python34\Testing')
I have a zip file containing thousands of mixed .xml and .csv files. I used the following to extract the zip file:
import zipfile
zip = zipfile.ZipFile(r'c:\my.zip')
zip.extractall(r'c:\output')
Now I need to extract the thousands of individual zip files contained in the 'c:\output' folder. I am planning on concatenating just the .csv files into one file. Thank you for the help!
Try this code :
import zipfile , os
zip = zipfile.ZipFile(r'c:/my.zip')
zip.extractall(r'c:/output')
filelist = []
for name in zip.namelist():
filelist.append(name)
zip.close()
for i in filelist:
newzip = zipfile.ZipFile(r'c:/output/'+str(i))
for file in newzip.namelist():
if '.csv' in file :
newzip.extract(file,r'c:/output/')
newzip.close()
os.remove(r'c:/output/'+str(i))
I am looking to unzip a particular folder from a .zip in Python:
e.g. archive.zip contains the folders foo and bar, I want to unzip foo to a specific location, retaining it's folder structure.
Check zipfile module.
For your case:
import zipfile
archive = zipfile.ZipFile('archive.zip')
for file in archive.namelist():
if file.startswith('foo/'):
archive.extract(file, 'destination_path')
You should close your zips....
import zipfile
archive = zipfile.ZipFile('archive.zip')
for file in archive.namelist():
if file.startswith('foo/'):
archive.extract(file, 'destination_path')
archive.close()
Or just use a safer method. With will close your zip.
import zipfile
with zipfile.ZipFile('archive.zip') as archive:
for file in archive.namelist():
if file.startswith('foo/'):
archive.extract(file, 'destination_path')
I like to reduce the list of names first so that the for loop doesn't parse through all the files in the zip archive:
import zipfile
archive = zipfile.ZipFile('archive.zip')
names_foo = [i for i in archive.namelist() if i.startswith('foo') ]
for file in names_foo:
archive.extract(file)
using zipfile library is very very slow.
this is better way:
os.system('unzip -P your-password path/to/file.zip')
Actually i am writting a script which writes two files into a desktop, let it be as "a.txt" and "b.txt"....... so after writing into a desktop i have to read this files and zip into a folder....
can anyone help on this....i know how to zip a folder but dono how to add two files in to a zip
Reading from folder i know its like this
def zipdir(basedir, archivename):
assert os.path.isdir(basedir)
with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
for root, dirs, files in os.walk(basedir):
for fn in files:
absfn = os.path.join(root, fn)
zfn = absfn[len(basedir)+len(os.sep):]
z.write(absfn, zfn)
if __name__ == '__main__':
import sys
basedir = sys.argv[1]
archivename = sys.argv[2]
zipdir(basedir, archivename)
The code which now i using is
import zipfile
zip = zipfile.ZipFile('Python.zip', 'a')
zip.write('fields.txt')
zip.write('grp.txt')
zip.close()
This is creating file of those two plus some extra folder which contains all files.......
you need to open the zip file with "a" -append parameter. Then you can use the write parameter without overwriting the file.
source: 12.4.1
EDIT:
zip.write('file.pdf','/folder/file.pdf')
The easiest wayh is to use shutil library. put all the files you want to zip in a single directoty(folder)
import shutil
shutil.make_archive(output_filename_dont_add_.zip, 'zip', directory_to_download)
Remember if you work with ipython you can use relative address for directory_to_download