7

I'm looking for a way to preserve the file attributes (eg. read-only) of a file that gets written to a zipfile.ZipFile instance.

The files I add to the zip archive gets their file attributes reset, eg. the read-only flag is gone when inspecting the archive with zip applications and after unzip.

My current environment is Windows and I'm having problems with the ZipInfo.external_attr method.

Surely there must be an standard way of preserving file attributes when writing to ZipFile?

Dharman
  • 30,962
  • 25
  • 85
  • 135
aelgn
  • 821
  • 1
  • 11
  • 17
  • Please edit your question and explain "I'm having problems". Otherwise, we can't help. – Aaron Digulla Jun 09 '10 at 15:29
  • The original question is valid. That was just a side note on the solutions here on stackoverflow diddnt work, since I'm not implementing for unix. Bad explanation though, point taken. – aelgn Jun 10 '10 at 14:48

1 Answers1

4

The problem I had was the heavily undocumented zipfile.ZipInfo.external_attr. All examples I found of this object refeered to the *nix file permission style.

My implementation will run on windows.

So I went about some "reverse engineering". Heh.

The magic number for windows read-only ZipInfo.external_attr is 33.

As in:

z = zipfile.ZipFile(targetFile, 'w')
(path, filename) = os.path.split(sourceFile)
bytes = file(sourceFile, 'rb')
info = zipfile.ZipInfo(filename)
info.external_attr = 33
z.writestr(info, bytes.read())
bytes.close()
z.close()

If you need to find the correct value for another type of attribute create the zipfile as you want it with some windows zip app and run this on it:

z = zipfile.ZipFile(sourceFile, 'r')
info = z.getinfo('fileToTest.ext')
print ("create_system", info.create_system)
print ("external_attr", info.external_attr)
print ("internal_attr", info.internal_attr)

Cheers!

aelgn
  • 821
  • 1
  • 11
  • 17
  • See also http://stackoverflow.com/questions/434641/how-do-i-set-permissions-attributes-on-a-file-in-a-zip-file-using-pythons-zipf/6297838#6297838 . You are right about the undocumented external_attr field. – Faheem Mitha Jun 09 '11 at 19:05
  • I got in to same problem while using "minizip" in windows to presereve all file attributes. I used the following code : DWORD attribs = GetFileAttributesW(szOut); zi.external_fa = attribs; – RP. Mar 05 '13 at 07:48