实现根据磁盘剩余容量,对剩余容量(预留了1GB)进行多次的写入和删除数据(次数为变量counts
)
每次写入1GB的数据(即变量data
),多次操作,以实现上述功能
通过更改taskTimes
变量可以多次写入和删除
from _datetime import datetime
import shutil
import os
def writeEraseDisk():
startTimeStamp = datetime.timestamp(datetime.now())
data = "*" * 1024 * 1024 * 1024 * 1
tmpFileName = "tmpFile"
if os.path.exists(tmpFileName):
os.remove(tmpFileName)
total, used, free = shutil.disk_usage("/")
print("The free disk space is [{} byte]({} GB)".format(free, free // (2 ** 30)))
counts = free // (2 ** 30) - 1
for count in range(counts):
start = datetime.timestamp(datetime.now())
with open(tmpFileName, 'a') as f:
f.write(data)
end = datetime.timestamp(datetime.now())
tmpTotal, tmpUsed, tmpFree = shutil.disk_usage("/")
print("\r", "{}/{}, run time: {} s, free {} GB".format(count + 1, counts, round(end - start, 3), tmpFree / (2 ** 30)), end="", flush=True)
if os.path.exists(tmpFileName):
os.remove(tmpFileName)
endTimeStamp = datetime.timestamp(datetime.now())
if round(endTimeStamp - startTimeStamp) < 60:
print("\nComplete an operation, total time: {} s\n".format(round(endTimeStamp - startTimeStamp, 2)))
elif 60 <= round(endTimeStamp - startTimeStamp) < 3600:
print("\nComplete an operation, total time: {} min\n".format(round((endTimeStamp - startTimeStamp) / 60, 2)))
elif 3600 <= round(endTimeStamp - startTimeStamp) < 86400:
print("\nComplete an operation, total time: {} h\n".format(round((endTimeStamp - startTimeStamp) / 60 / 60, 2)))
else:
print("\nComplete an operation, total time: {} s\n".format(endTimeStamp - startTimeStamp, 2))
if __name__ == '__main__':
taskTimes = 3
for task in range(taskTimes):
print("task {}/{}".format(task+1, taskTimes))
writeEraseDisk()