Zip single file - python

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

Related

how can i adding custom path for saving the zip_file

I am creating a zip file using the zipfile module. It works like a charm. but that'sĀ file, saved in the executed script place.
my script path is a:
[b]c:/User/Administrator/[/b]script.py
and the zipfile saved in:
[b]c:/User/Administrator/[/b]backup.zip
but I want, [b]creating a zipfile, in another path[/b], like this:
[b]d:/backups/[/b]backup.zip
my code like this:
import zipfile
zip_file = zipfile.ZipFile("backup.zip", 'w')
with zip_file:
for file in filePaths:
zip_file.write(file)
my question is a how can I adding custom path for saving the zip_file. because I have not an enough space in C:
tnx a lot.
Give the path you want to ZipFile function.
When you give only the name of the file, it will save the file in the current directory which the program is running.
Do this instead:
import zipfile
# For example you want to save it in drive 'D'
path = "D:\\PathToYourDir\\backup.zip"
zip_file = zipfile.ZipFile(path, 'w')
with zip_file:
for file in filePaths:
zip_file.write(file)

read an zip file object by pycdf without unzipping

I know how to open a file in a zip file without unzipping. It can be done as follows:
import zipfile
archive = zipfile.ZipFile(path_to_zipfile, 'r')
my_zipfile = archive.open('file_01.cdf') # "file_01.cdf" is contained in the zipfile
My problem is: the file "file_01.cdf" contained in the zip file is in CDF format. Normally, a CDF format file can be read as follows:
from spacepy import pycdf
cdf_file = pycdf.CDF(path_to_file)
data = cdf_file.copy()
The problem is: function pycdf.CDF accept argument in string format. However, I want to pass an zipfile object as an argument to pycdf.CDF function. (Because I don't unzip the zip file, I don't have path to file as a string). Any idea to overcome this problem? Thank you very much!
I know you specifically asked about doing it without unzipping but I think that's not possible (someone will correct me if I'm wrong, I hope).
You could do something like:
import zipfile
import os
import tempfile
import shutil
path = r'C:\Users\XXX\Desktop\test.zip' # my zip file
archive = zipfile.ZipFile(path, 'r')
tmpdir = tempfile.mkdtemp(dir=os.getcwd()) # create a temp folder in the working directory
archive.extract('test.txt', path=tmpdir) # extract your file to the temp folder
path_to_my_file = os.path.join(tmpdir, 'test.txt') # this is the path to the extracted file
# -------
# do stuff with your file path
# -------
print(path_to_my_file)
shutil.rmtree(tmpdir) # delete the temp folder

How to compress a file with shutil.make_archive in python?

I want to compress one text file using shutil.make_archive command. I am using the following command:
shutil.make_archive('gzipped'+fname, 'gztar', os.path.join(os.getcwd(), fname))
OSError: [Errno 20] Not a directory: '/home/user/file.txt'
I tried several variants but it keeps trying to compress the whole folders. How to do it correctly?
Actually shutil.make_archive can make one-file archive! Just pass path to target directory as root_dir and target filename as base_dir.
Try this:
import shutil
file_to_zip = 'test.txt' # file to zip
target_path = 'C:\\test_yard\\' # dir, where file is
try:
shutil.make_archive(target_path + 'archive', 'zip', target_path, file_to_zip)
except OSError:
pass
shutil can't create an archive from one file. You can use tarfile, instead:
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
os.chdir('/home/user')
tar.add("file.txt")
tar.close()
or
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
tar.addfile(tarfile.TarInfo("/home/user/file.txt"), "/home/user/file.txt")
tar.close()
Try this and Check shutil
copy your file to a directory.
cd directory
shutil.make_archive('gzipped', 'gztar', os.getcwd())
#CommonSense had a good answer, but the file will always be created zipped inside its parent directories. If you need to create a zipfile without the extra directories, just use the zipfile module directly
import os, zipfile
inpath = "test.txt"
outpath = "test.zip"
with zipfile.ZipFile(outpath, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.write(inpath, os.path.basename(inpath))
If you don't mind doing a file copy op:
def single_file_to_archive(full_path, archive_name_no_ext):
tmp_dir = tempfile.mkdtemp()
shutil.copy2(full_path, tmp_dir)
shutil.make_archive(archive_name_no_ext, "zip", tmp_dir, '.')
shutil.rmtree(tmp_dir)
Archiving a directory to another destination was a pickle for me but shutil.make_archive not zipping to correct destination helped a lot.
from shutil import make_archive
make_archive(
base_name=path_to_directory_to_archive},
format="gztar",
root_dir=destination_path,
base_dir=destination_path)

How to unzip specific folder from a .zip with Python

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')

How to add multiple files into a single zip folder

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

Categories

Resources