1. 程式人生 > 其它 >生成指定大小的檔案,如:字典型別,json型別,整型等

生成指定大小的檔案,如:字典型別,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)