在python中写一本字典

时间:2017-01-12 01:47:10

标签: python numpy dictionary

from random import randint    
import threading              
import numpy as np



def gen_write():
    threading.Timer(10.0, gen_write).start()  
    with open("pins.npy", "w") as f:
        f.close()

    data = {}
    for x in range(5):
        pin = randint(99, 9999)
        pins_for_file = pin
        with open('pins.npy', 'a') as f:
            data[x + 1] = pins_for_file
            np.save(f, data)



gen_write()

所以,这就是问题所在,我用numpy写了一个字典到一个文件但不知何故,它只保存了第一个,我已经改变了for循环了几十次而且我无法得到右循环,至少我认为问题来自那里。 顺便说一句,我是python的新手。

提前致谢 问候

1 个答案:

答案 0 :(得分:0)

首先,您可以在循环外打开它,而不是在循环内打开文件 其次,您不需要使用with语句明确关闭您打开的文件,这是使用with的重点之一。 所以我设想的代码修改如下:

import threading
from sys import getsizeof
from random import randint
import numpy as np

def gen_write():
    #threading.Timer(10.0, gen_write).start()
    data = {}
    with open("pins.npy", "w") as f:
        for x in range(5):
            pin = randint(99, 9999)
            pins_for_file = pin
            data[x+1] = pins_for_file

        np.save(f, data)

gen_write()  

或更好可能使用python pickle模块来保存字典,所以:

import threading
from sys import getsizeof
from random import randint
import pickle

def gen_write():
    #threading.Timer(10.0, gen_write).start()
    data = {}
    with open("pins.pkl", "w") as f:
        for x in range(5):
            pin = randint(99, 9999)
            pins_for_file = pin
            data[x+1] = pins_for_file

        pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

gen_write()

另外,我评论threading.Timer(10.0, gen_write).start(),因为我正在为我奔跑 另一种方法是将字典保存在json文件中,这是一种常用的文件格式。为此,您将执行以下操作:

import threading
from sys import getsizeof
from random import randint
import json

def gen_write():
    #threading.Timer(10.0, gen_write).start()
    data = {}
    with open("pins.json", "w") as f:
        for x in range(5):
            pin = randint(99, 9999)
            pins_for_file = pin
            data[x+1] = pins_for_file

        json.dump(data, f)

gen_write()