我如何在python中压缩文件而不写入所有目录 [英] How do i zip files in python without all directories written to it

查看:374
本文介绍了我如何在python中压缩文件而不写入所有目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试压缩多个文件,但是当我打开zip文件时,遇到了一个奇怪的问题,所有导致该文件的目录也被列出了
home / site / Uploads / test /

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/test/

这是我编写的python代码

Here is the python code i have written

import os
import zipfile

zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("D:/home/site/Uploads/test/"):
zf.write(dirname)
for filename in files:
    zf.write(os.path.join(dirname, filename))
zf.close()

压缩文件很好但是为什么也是列出的所有其他目录。

The zipped files are fine but why is every other directory listed too.

我得到了这样的zip文件
-> home-> site-> Uploads-> test- -> file.txt
我想要的是这个
-> file.txt

I got the zip file like this -->home-->site-->Uploads-->test-->file.txt what i wanted was this -->file.txt

推荐答案

让假定以下目录结构:

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

只需设置正确的弧名:

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

解压缩显示如下所示的zip文件:

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

这篇关于我如何在python中压缩文件而不写入所有目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆