Json和npy文件的读写

发布于 2022-10-25  457 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

整理旧代码,记录一下

Json文件的读写

import json, sys

def saveToJSON(filename, dicObject):
    flag = False
    if type(dicObject)!=dict:
        return flag
    try:
        j_file = open(filename,'w')
        json.dump(dicObject, j_file, ensure_ascii = False)
        flag = True
    except:
        print('往%s写数据出错'%(filename))
    finally:
        if flag:
            j_file.close()
        return flag


def GetFromJSON(filemame):
    flag = False
    dicObject = {}
    try:
        j_file = open(filename,'r')
        dicObject = json.load(j_file)
        flag = True
    except:
        print('从%s读JSON文件数据出错!'%(filename))
    finally:
        if flag:
            j_file.close()
    return dicObject


if __name__ == '__main__':
    d_student = {'name':'丁丁','age':'12','birthday':'2006年12月25日'}
    filename = 'student.json'
    f_OK = saveToJSON(filename,d_student)
    if f_OK:
        print('学生信息保存到JSON文件成功!')
    else:
        sys.exit()
    d_get_s = GetFromJSON(filename)
    if d_get_s:
        print(d_get_s)

npy文件

import numpy as np
import time

# 1 million samples
n_samples=1000000
# Write random floating point numbers as string on a local CSV file
with open('fdata.txt', 'w') as fdata:
    for _ in range(n_samples):
        fdata.write(str(10*np.random.random())+',')
# Read the CSV in a list, convert to ndarray (reshape just for fun) and time it
t1=time.time()
with open('fdata.txt','r') as fdata:
    datastr=fdata.read()
lst = datastr.split(',')
lst.pop()
array_lst=np.array(lst,dtype=float).reshape(1000,1000)
t2=time.time()
print(array_lst)
print('\nShape: ',array_lst.shape)
print(f"Time took to read: {t2-t1} seconds.")

np.save('fnumpy.npy', array_lst)

t1=time.time()
array_reloaded = np.load('fnumpy.npy')
t2=time.time()
print(array_reloaded)
print('\nShape: ',array_reloaded.shape)
print(f"Time took to load: {t2-t1} seconds.")
届ける言葉を今は育ててる
最后更新于 2022-11-07