生成指定大小的文件,如:字典类型,json类型,整型等
# -*- coding:utf-8 -*- # 生成指定大小文件 import json import os import random import numpy as np # 生成指定大小的文件 def genSizeFile(filename, filesize): file_path = "Data" +filename + ".txt" ds = 0 with open(file_path, "w") as f: while ds < filesize: f.write(str(round(random.uniform(-1000, 1000),2))) f.write("\n") ds = os.path.getsize(file_path) print(ds) # 生成指定数量 def genNfile(fileNum): numCount = fileNum numRange = 3*numCount tmpList = random.sample(range(numRange), numCount) print(tmpList) i = 0 filePath = "" + str(numCount) + ".txt" with open(filePath, "w") as f: while i < numCount: f.write(str(tmpList[i])) f.write("\n") i += 1 ds = os.path.getsize(filePath) print(ds) # 查看文件记录数 def countLine(thefilepath): count = 0 with open(thefilepath, 'rb') as thefile: while True: buffer = thefile.read(100*1024*1024) if not buffer: break count += str(buffer).count("\n") print(count) def genJsonFileSize(KB): dic = {"power_switch": True, "color": 2, "message": "mece", "low_voltage": 24.6, "time": "202205111006" } flag = 0 size = 0 dic_json = {} while size < KB * 1024: for i in dic.keys(): dic.update({i + str(flag): dic[i]}) dic_json = json.dumps(dic) # 字典转json with open('./data.json', 'w') as f: f.write(dic_json) size = os.path.getsize('./data.json') flag += 1 print(dic_json) size_KB1 = size / 1024 size_KB2 = size % 1024 size = str(size_KB1) + '.' + str(size_KB2) print('dicsize:', size) return dic # 此处 传入的dic是作为str类型传入的 def join_json_file(dic): json_content = json.dumps({ "type": "update", "version": 0, "state": { "reported": dic, }, "clientToken": "client_token2" }) with open('./json_data.json', 'w') as f: f.write(str(json_content)) size = os.path.getsize('./json_data.json') size_KB1 = size / 1024 size_KB2 = size % 1024 size = str(size_KB1) + '.' + str(size_KB2) print('jsonsize:', size) if __name__ == '__main__': #dic = genJsonFileSize(10) # join_json_file(dic) with open('./adjust.json', 'r') as f: content = f.read() print('content', len(content)) size = os.path.getsize('./adjust.json') size_KB1 = size / 1024 size_KB2 = size % 1024 size = str(size_KB1) + '.' + str(size_KB2) print('jsonsize:', size)
本文来自博客园,作者:ReluStarry,转载请注明原文链接:https://www.cnblogs.com/relustarry/p/16258694.html