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

Har*_*mbe 7 python zip zipfile

我有一个test.txtzip存档内的文件test.zip.test.txt当压缩时,权限不受我的控制,但现在我希望它们可以进行组写.我正在使用Python解压缩文件,并且不想逃避到shell.

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

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()
Run Code Online (Sandbox Code Playgroud)

这在使用2.5.1的OS X上完美运行,但它在我的主页框(Debian,Python 2.4和2.5)或使用Python 2.4的RHEL 5上不起作用.除了OS X之外,它不会出错,但也不会更改权限.有什么想法吗?另外,writestr()工作怎么样?我知道我在这里错误地使用它.

有没有办法在没有的情况下执行此操作os.chmod(提取文件的用户在提取os.chmod后没有权限使用)?我对zip文件有完全写入权限.

更多信息:

> 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
Run Code Online (Sandbox Code Playgroud)

用户提取不是myuser,但是在mygroup.

Pet*_*org 6

我和你有类似的问题,所以这是我的东西中的代码spinet,我相信这应该在这里有所帮助。

# 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
Run Code Online (Sandbox Code Playgroud)

您可能会做类似的事情,但插入您自己的逻辑来计算您的烫发值。我应该注意,我在这里使用的是 Python 2.5,我知道与 Python 的 zipfile 支持的某些版本存在一些不兼容性。


Chr*_*ris 1

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

既然你不能这样做,你将不得不尝试做你想做的事情(并让它在 Debian 下工作。)

Python 的 zipfile 库存在许多问题,包括将 writestr 的模式设置为在某些系统上写入的文件的模式,或者将 zip 系统设置为 windows 而不是 unix。因此,不一致的结果可能意味着什么都没有改变。

所以你可能完全不走运。