How do i zip files in python without all directories written to it

前端 未结 1 668
时光取名叫无心
时光取名叫无心 2021-01-26 06:54

Im trying to zip multible files but i have run into a strange problem when i opened the zip file all directories leading to the files are listed as well home/site/Uploads/

1条回答
  •  囚心锁ツ
    2021-01-26 07:17

    Lets assume the following directory structure:

    ./uploads
    └── foo
        └── bar
            ├── 1.txt
            └── baz
                └── 2.txt
    

    You just need to set the arcname correct:

    import os
    import zipfile
    
    zf = zipfile.ZipFile("myzipfile.zip", "w")
    for dirname, subdirs, files in os.walk("/tmp/uploads"):
        for filename in files:
            zf.write(os.path.join(dirname, filename), arcname=filename)
    zf.close()
    

    Unzip shows the zip file like this:

    unzip -l myzipfile.zip                                                                                                                    Archive:  myzipfile.zip
      Length      Date    Time    Name
    ---------  ---------- -----   ----
            0  10-21-2019 15:03   1.txt
            0  10-21-2019 15:03   2.txt
    ---------                     -------
            0                     2 files
    

    0 讨论(0)
提交回复
热议问题