代码之家  ›  专栏  ›  技术社区  ›  Harley Holcombe

在python中设置对压缩文件的权限

  •  7
  • Harley Holcombe  · 技术社区  · 16 年前

    test.txt 在一个压缩文件里 test.zip . 上的权限 test.txt文件

    编辑: 到目前为止我得到的是:

    import zipfile
    
    z = zipfile.ZipFile('test.zip', 'w')
    zi = zipfile.ZipInfo('test.txt')
    zi.external_attr = 0777 << 16L
    z.writestr(zi, 'FOO')
    z.close()
    
    z = zipfile.ZipFile('test.zip', 'r')
    for name in z.namelist():
        newFile = open(name, "wb")
        newFile.write(z.read(name))
    
        newFile.close()
    z.close()
    

    writestr() 工作?我知道我用错了。

    os.chmod (提取文件的用户没有权限使用 操作系统chmod

    更多信息:

    > ls -l test.zip
    -rwxrwxrwx 1 myuser mygroup 2008-11-11 13:24 test.zip
    > unzip test.zip
    Archive:  test.zip
      inflating: test.txt 
    > ls -l test.txt
    -rw-r--r-- 1 myuser mygroup 2008-11-11 13:34 test.txt
    

    用户提取不是 myuser mygroup .

    3 回复  |  直到 16 年前
        1
  •  4
  •   Petriborg    16 年前

    我有一个类似的问题,所以这里是我的东西的代码尖刺,我相信这应该有帮助。

    # extract all of the zip
    for file in zf.filelist:
        name = file.filename
        perm = ((file.external_attr >> 16L) & 0777)
        if name.endswith('/'):
            outfile = os.path.join(dir, name)
            os.mkdir(outfile, perm)
        else:
            outfile = os.path.join(dir, name)
            fh = os.open(outfile, os.O_CREAT | os.O_WRONLY , perm)
            os.write(fh, zf.read(name))
            os.close(fh)
        print "Extracting: " + outfile
    

    你可以做一些类似的事情,但是插入你自己的逻辑来计算你的perm值。我应该注意到,我在这里使用的是Python2.5,我知道一些版本的Python的zipfile支持存在一些不兼容性。

        2
  •  1
  •   Chris    16 年前

    根据文档,unzip将权限设置为unix下存储的权限。另外,不使用shell umask。你最好的办法是在压缩文件之前确定烫发已经设置好。

    既然你不能这么做,你就必须尝试去做你想做的事情(并让它在Debian下工作)

    Pythons zip file库有很多问题,包括将writestr的模式设置为在某些系统上写入的文件的模式,或者将zip系统设置为windows而不是unix。所以你前后矛盾的结果可能意味着一切都没有改变。

        3
  •  0
  •   John Fouhy    16 年前

    解压缩到stdout(unzip-p)并重定向到文件?如果zip中有多个文件,可以列出zip内容,然后一次提取一个。

    for n in `unzip -l test.zip | awk 'NR > 3 && NF == 4 { print $4 }'`; do unzip -p test.zip $n > $n; done