Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import os
- import sys
- import hashlib
- import random
- import tarfile
- import shutil
- import subprocess
- # Files by size (sorted ascending)
- filist = filter(lambda x: os.path.isfile(os.path.join(sys.argv[1], x)), os.listdir(sys.argv[1]))
- filist = sorted(filist, key=lambda x: os.stat(os.path.join(sys.argv[1], x)).st_size)
- # Folders by size (sorted ascending)
- _fslist1 = filter(lambda x: os.path.isdir(os.path.join(sys.argv[1], x)), os.listdir(sys.argv[1]))
- _fslist2 = list()
- for dir in _fslist1:
- path = os.path.join(sys.argv[1], dir)
- total_size = 0
- for dirpath, dirnames, filenames in os.walk(path): # walk directory for file sizes
- for i in filenames:
- total_size += os.path.getsize(os.path.join(dirpath, i))
- _fslist2.append({'name': path, 'size': total_size})
- folist = list()
- for dirobj in list(sorted(_fslist2, key=lambda x: x['size'])):
- folist.append(dirobj['name'])
- # Totals
- files = list(filist) + list(folist)
- try:
- os.mkdir(sys.argv[1]+'_tar') # create dir if not exist
- except:
- pass
- for file in files:
- bfn = os.path.join(sys.argv[1], file)
- while True:
- try: #generate random name
- rb = random.getrandbits(256)
- bytearray.fromhex('{:x}'.format(rb)).hex() + '.tar'
- except: # this code can break but too lazy to fix it so just retry
- continue
- else:
- fn = bytearray.fromhex('{:x}'.format(rb)).hex() + '.tar'
- break
- print(bfn)
- ## Python-native tar
- #with tarfile.open(os.path.join(sys.argv[1]+'_tar', fn), "w:") as tar:
- # tar.add(bfn, arcname=os.path.basename(bfn))
- # tar.close()
- ## System tar (much faster)
- try:
- subprocess.check_output(['tar', 'cf', os.path.join(sys.argv[1]+'_tar', fn), '-C', sys.argv[1], os.path.basename(bfn)])
- except subprocess.CalledProcessError as exc:
- raise Exception(f'tar broke: {exc.returncode}: {exc.output}')
- else:
- if os.path.isfile(bfn) or os.path.islink(bfn):
- os.remove(bfn) # remove the file
- elif os.path.isdir(bfn):
- shutil.rmtree(bfn) # nuke dir
- else:
- print(f'path {bfn} is not a file, dir or symlink, not deleting...')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement