Last active 1440820549

Sum up the total size of the contents of a folder of torrents

torrentdirsum.py Raw
1import libtorrent as lt
2from os import listdir
3import json
4
5def sizeof_fmt(num):
6 for x in ['bytes','KB','MB','GB']:
7 if num < 1024.0 and num > -1024.0:
8 return "%3.1f%s" % (num, x)
9 num /= 1024.0
10 return "%3.1f%s" % (num, 'TB')
11
12x = 1
13dirlist = listdir('.')
14
15def main(dirlist):
16 total = []
17 x = 1
18 try:
19 with open('cache.json') as f:
20 cache = json.loads(f.read())
21 except:
22 cache = {}
23 try:
24 for a in dirlist:
25 if not a.split(".")[-1] == "torrent":
26 continue
27 if not a in cache:
28 info = lt.torrent_info(lt.bdecode(open(a, 'rb').read()))
29 tot = info.total_size()
30 cache[a] = tot
31 else:
32 tot = cache[a]
33 total.append(tot)
34 print str(cache[a]) + " %s/%s" % (x, len(dirlist))
35 x += 1
36 finally:
37 with open('cache.json', 'w') as f:
38 f.write(json.dumps(cache))
39 return total
40
41if __name__ == "__main__":
42 dirlist = listdir('.')
43 total = main(dirlist)
44 print sizeof_fmt(sum(total))