Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python/zip: How to eliminate absolute path in zip archive if absolute paths for files are provided?

I have two files in two different directories, one is '/home/test/first/first.pdf', the other is '/home/text/second/second.pdf'. I use following code to compress them:

import zipfile, StringIO buffer = StringIO.StringIO() first_path = '/home/test/first/first.pdf' second_path = '/home/text/second/second.pdf' zip = zipfile.ZipFile(buffer, 'w') zip.write(first_path) zip.write(second_path) zip.close() 

After I open the zip file that I created, I have a home folder in it, then there are two sub-folders in it, first and second, then the pdf files. I don't know how to include only two pdf files instead of having full path zipped into the zip archive. I hope I make my question clear, please help. Thanks.

like image 647
Shang Wang Avatar asked Apr 18 '13 19:04

Shang Wang


People also ask

How do you change the absolute path in Python?

Use abspath() to Get the Absolute Path in Python Under the Python module os are useful utility functions and properties that manipulate and access file paths under the os. path property. To get the absolute path using this module, call path. abspath() with the given path to get the absolute path.

How do you know if a path is absolute or relative in Python?

path. isabs() method in Python is used to check whether the specified path is an absolute path or not. On Unix platforms, an absolute path begins with a forward slash ('/') and on Windows it begins with a backward slash ('\') after removing any potential drive letter.

What is an absolute Filepath?

An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

How do I know if my path is absolute?

You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.


1 Answers

The zipfile write() method supports an extra argument (arcname) which is the archive name to be stored in the zip file, so you would only need to change your code with:

from os.path import basename ... zip.write(first_path, basename(first_path)) zip.write(second_path, basename(second_path)) zip.close() 

When you have some spare time reading the documentation for zipfile will be helpful.

like image 82
João Pinto Avatar answered Sep 19 '22 23:09

João Pinto