使用背景
通过自动在设备文件资源管理器中生成指定大小的数据文件,代替手动拖动文件。
调用库
1 2 3 4
| import os import sys import time import shutil
|
生成数据函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| def generate_large_file(size): """ 本函数用于在硬盘上生成一个文件,并不断向其中写入数据,直到文件达到指定的大小。 如果指定的生成数据大小大于文本文件最大存储空间(3.99G,4293918720字节)的话,则会新建以当前时间命名的新文件并不断写入数据,以此往复。
使用时,只需要设置想要生成数据的最大大小,单位为G :param size: 本次生成数据总计最大大小(G) """
data = '0' * 1024 * 1024 increment_size = len(data) size = float(size) * 1024 * 1024 * 1024 file_name = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) file_path = f"F:/{file_name}.txt"
with open(file_path, 'a') as f: total_size = 0 while True: f.write(data) total_size += increment_size print(f"当前文件大小:{os.path.getsize(file_path) / 1048576} MB") if total_size >= size: print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) sys.exit() if os.path.getsize(file_path) >= 1 * 1024 * 1024 * 1024: time.sleep(2)
|
重复复制文件函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| def mycopyfile(size): """本函数用于将硬盘中指定位置的一个文件复制到新的指定位置,直到文件达到指定的大小""" source_file = r"F:\20240901\20240901080000.log" destination_folder = r"F:\20240811" count = int(float(size) * 1024 * 1048576 / os.path.getsize(source_file)) if not os.path.exists(destination_folder): os.makedirs(destination_folder) while True: for i in range(1, count + 1): name = f"20240901080000{i}.log" destination_file = os.path.join(destination_folder, name) shutil.copy2(source_file, destination_file) nowtime = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) print(f"{nowtime} 当前复制文件为{name} 已经生成数据大小为:{round((float(size) / count) * i, 3)}") if i == count: sys.exit()
|
主函数
1 2 3 4 5 6 7 8 9 10
| max_size = input("请输入希望生成数据的总大小(单位:G):")
while True: try: generate_large_file(max_size) except OSError: print("EMMC还没有上线呢!") time.sleep(20)
|