6

I know that you can get the size in bytes of a file in a ZIP file using the .file_size method But is there any what I can get the size of a folder instead?

Ex:

import zipfile, os

os.chdir('C:\\')    
zp= zipfile.ZipFile('example.zip')

spamInfo = zp.getinfo('spam.txt')    #Here, Instead of a file I'd like to put a folder
spamInfo.file_size

zp.close()
Dharman
  • 30,962
  • 25
  • 85
  • 135
tadm123
  • 8,294
  • 7
  • 28
  • 44
  • 1
    You might need to loop for the files in the folder. Then get the info with zp.getinfo('file'). Then just increase a variable with the file_size each time. – Mirage Oct 10 '16 at 07:11
  • 2
    `sum(zp.getinfo(filename).file_size for filename in folder)`? – Peter Wood Oct 10 '16 at 07:13
  • Sorry for the dumb question, I'm new in this but what's the correct way of writing a folder. Example. If I have a folder named 'Drawings' on the zip file. should I put = > for filename in '\\Drawings'? – tadm123 Oct 10 '16 at 21:00

1 Answers1

18
import zipfile

zp = zipfile.ZipFile("example.zip")

size = sum([zinfo.file_size for zinfo in zp.filelist])
zip_kb = float(size) / 1000  # kB
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Naresh Chaudhary
  • 705
  • 5
  • 14
  • 3
    You don't need to build a list, `sum` will work with the comprehension expression. – Peter Wood Oct 14 '16 at 09:27
  • 1
    This only work for reliable zip sources, it is no reliable for user/attacker-origin source, for that you have to physically read through the files - read and count bytes as you go. – jave.web Nov 07 '20 at 12:53
  • Hi, is there any way to vectorize this instead of the for loop and get the output in a dataframe? – Rohan Apr 12 '23 at 07:39