Code: Alles auswählen
# Code for shortening files by tomba 2015
# Usage: cutfromfile(filepath,length)
import os
def percentage(part, whole):
return 100 * float(part)/float(whole)
def getfreespace(path):
if(os.name == "nt"):
import ctypes
space = ctypes.c_ulonglong(0)
diskname = path.split("\\")[0]+"\\"
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(diskname), None, None, ctypes.pointer(space))
return space.value
else:
space = os.statvfs(path)
return space.f_bavail * space.f_frsize
def cutfromfile(filename,length,chunksize=131072,verbose=True):
if not(os.path.isfile(filename)):
if(verbose):print("File not found!")
return 1
if(chunksize > 524288):
if(verbose):print("Too big chunks!")
return 2
if(os.path.getsize(filename) * 2 > getfreespace(os.path.abspath(filename)[:-len(filename)+1])):
if(verbose):print("Too less free space on your disk!")
return 3
if(os.path.getsize(filename) <= chunksize * 3):
fs = open(filename,"rb")
cnt = fs.read()
fs.close()
os.remove(filename)
nf = open(filename,"wb")
nf.write(cnt[:-length])
nf.close()
return 0
fs = open(filename,"rb")
total_len = 0
while True:
new_chunk = fs.read(chunksize)
if not(new_chunk):
break
total_len += len(new_chunk)
fs.close()
os.rename(filename,filename+".old")
new_file = open(filename,"wb")
old_file = open(filename+".old","rb")
dif = total_len - length
if(verbose):print("Cutting %s from file with size %s (%s Percent) (%s bytes will remain)") % (str(length),str(total_len),str(int(100-percentage(dif,total_len))),str(int(dif)))
amount = int(dif/chunksize)
rest = int(dif % chunksize)
for x in range(0,amount):
chunk = old_file.read(chunksize)
new_file.write(chunk)
rest_chunk = old_file.read(rest)
new_file.write(rest_chunk)
old_file.close()
new_file.close()
os.remove(filename+".old")
if(verbose):print("Completed re-writing")
return 0