用python编写词典

用python编写词典,python,numpy,dictionary,Python,Numpy,Dictionary,所以,这就是问题所在,我用numpy将一个字典写入一个文件,但不知怎的,它只保存了第一个,我已经更改了for循环几十次,但我无法获得正确的循环,至少我认为问题来自于此。 顺便说一句,我是python新手 提前谢谢 问候语首先,您可以在循环外部打开文件,而不是在循环内部打开文件。 其次,不需要使用with语句显式关闭打开的文件,这是使用with的要点之一 因此,我设想的代码修改如下: from random import randint import threading

所以,这就是问题所在,我用numpy将一个字典写入一个文件,但不知怎的,它只保存了第一个,我已经更改了for循环几十次,但我无法获得正确的循环,至少我认为问题来自于此。 顺便说一句,我是python新手

提前谢谢
问候语

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

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()
或者最好使用python模块保存字典,因此:

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()  
此外,我还对threading.Timer(10.0,gen_write).start()进行了注释,因为它对我来说永远都在运行。
另一种方法是将字典保存在json文件中,这是一种常用的文件格式。为此,您将执行以下操作:

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()

你不能复制问题里面的代码吗?因为人们更容易获取和尝试。为什么在这里使用numpy?将代码粘贴为文本并学习如何设置问题的格式。总之,我很确定np.save不适用于“a”选项。文件格式的第一部分指定了数据,当您追加时,这些数据永远不会被覆盖,因此它只知道如何读取您第一次写入的内容。您应该使用
np.save
来保存numpy数组。在字典中使用pickle或JSON。@juanpa.arrivillaga那么我如何才能使它保存我想写的所有内容,因为我发布了python的新消息,但我仍然不太了解它,感谢关于numpy的提示,我决定使用numpy,因为JSON对我不起作用,关于模块hanks还有很多需要学习,它在保存字典方面起到了作用,但我还想访问其中一个字典条目,只有一个,这就是我使用numpy的原因,使用numpy,您可以访问一个条目,我想我认为您可以使用这两种方法在打开文件阅读时访问您想要的条目。
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()