0

I want to add an image in a directory under a zip. The structure of the zip is the following:

doc1.zip

├── word
|   ├── media
|       ├── img1.png
|       └── img2.png

I want to add the picture soc_logo under media. I wrote the following code:

with zipfile.ZipFile(zip_copy_filename, "w") as documentx:
        for filename in filenames:
            if filename=='word/media/soc_logo.png':
                documentx.write(os.path.join(tmp_dir,filename))
            else:
                documentx.write(os.path.join(tmp_dir,filename), filename)

But the result is the following:

doc1.zip

├── temp
|   ├── /tmpT6kmaW/word/media/
├── word
|   ├── media
|       ├── img1.png
|       └── img2.png

Any help please ?

rafaelc
  • 57,686
  • 15
  • 58
  • 82
Kais Dkhili
  • 399
  • 1
  • 5
  • 18
  • This seems to be the expected result of the first branch of the `if` statement, which fails to supply an `arcname` parameter and thus writes a file with full pathname (including the temporary directory) into the `ZipFile`. (a) What is the first branch supposed to achieve? (b) Are you sure the `else` branch is ever taken? (c) is the white space between before `.png` intentional? – dhke Oct 13 '15 at 12:04
  • Archive names should be relative to the archive root, that is, they should not start with a path separator. https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.write – Noxeus Oct 13 '15 at 12:05
  • hello, the if is to separate between existed files in the wzip and not existed files, thats mean that word/media/soc_logo.png not existed in the zip. so i should create it. i edited the question and i correct the white space – Kais Dkhili Oct 13 '15 at 12:11
  • This answer should help you: http://stackoverflow.com/a/459242/5388440 – Noxeus Oct 13 '15 at 12:20

0 Answers0