Chris_007
Chris_007

Reputation: 923

Zip file and save to specific folder

this might be a silly question but I'm struggling a lot finding solution to it.

So I have a file in the given folder:

Output\20190101_0100\20190101_0100.csv

Now I want to zip the file and save it to same location. So here's my try:

zipfile.ZipFile('Output/20190101_0100/20190101_0100_11.zip', mode='w', compression=zipfile.ZIP_DEFLATED).write('Output/20190101_0100/20190101_0100_11.csv')

But it's making a folder insider zip folder and saving it, as shown below:

Output\20190101_0100\20190101_0100_11.zip\Output\20190101_0100\20190101_0100_11.csv

Can someone tell me how can I save my file directly in the same location or location mentioned below:

Output\20190101_0100\20190101_0100_11.zip\20190101_0100_11.csv

Upvotes: 0

Views: 2265

Answers (2)

de1
de1

Reputation: 3124

Rephrasing of question

The question is slightly confusing because Output\20190101_0100\20190101_0100_11.zip\Output\20190101_0100\20190101_0100_11.csv won't be a file, but rather Output\20190101_0100\20190101_0100_11.csv will be a file within the zip file Output\20190101_0100\20190101_0100_11.zip (if I am not mistaken)

Just to restate your problem (if I understood it correctly):

  • You have a file Output\20190101_0100\20190101_0100.csv (a file 20190101_0100.csv in the Output -> 20190101_0100 sub directory)
  • You want to create the zip file Output/20190101_0100/20190101_0100_11.zip (20190101_0100_11.zip in the Output -> 20190101_0100.zip directory)
  • You want to add the aforementioned CSV file Output\20190101_0100\20190101_0100.csv but without the leading path, i.e. as 20190101_0100_11.csv rather than Output\20190101_0100\20190101_0100.csv.

Or to not get confused with too many similar directories, let's simplify it as:

  • You have a file test.csv in the sub directory sub-folder
  • You want to create the zip file test.zip
  • You want to add the aforementioned CSV file test.csv but without the leading path, i.e. as test.csv rather than sub-folder/test.csv.

Answer

From the ZipFile.write documentation:

Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed).

That means that arcname will default to the passed in filename (it doesn't have a drive letter or leading path separator).

If you want to remove the sub folder part, just pass in arcname as well. e.g.:

import zipfile

with zipfile.ZipFile('path-to-zip/test.zip', 'w') as zf:
    zf.write('sub-folder/test.csv', arcname='test.csv')

Upvotes: 2

Shidouuu
Shidouuu

Reputation: 409

You could try using a raw path:

zipfile.ZipFile('Output/20190101_0100/20190101_0100_11.zip', mode='w', compression=zipfile.ZIP_DEFLATED).write(r'C:\...\Output\20190101_0100\20190101_0100_11.csv')

Upvotes: 0

Related Questions