【问题标题】:Writing a dictionary in python用python写字典
【发布时间】:2017-05-27 00:11:35
【问题描述】:
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 新手。

提前致谢 问候

【问题讨论】:

  • 您不能复制问题中的代码吗?因为人们更容易获得和尝试。
  • 你为什么在这里使用 numpy?
  • 将代码粘贴为文本并学习如何格式化您的问题
  • 无论如何,我很确定 np.save 不适用于“a”选项。文件格式的第一部分指定了数据,当你追加时,它永远不会被覆盖,所以它只知道如何读取你第一次写的内容。您应该使用 np.save 来保存 numpy 数组。对字典使用 pickle 或 JSON。
  • @juanpa.arrivillaga 那么我怎样才能让它保存我想写的所有东西,因为我发布了我对 python 的新手,但我仍然不太了解它,谢谢关于 numpy 的提示,我决定使用 Numpy,因为 JSON 不适合我,关于模块还有很多东西要学习

标签: python numpy dictionary


【解决方案1】:

首先,您可以在循环外打开文件,而不是在循环内打开文件。
其次,您不需要使用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()

【讨论】:

  • 谢谢,它可以保存字典,但我也想访问其中一个字典条目,只有一个,这就是我使用 numpy 的原因,我认为使用 numpy 你只能访问一个项目
  • 我认为当您打开文件进行阅读时,您可以使用这两种方法访问您想要的条目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 2021-05-15
  • 2010-10-20
  • 2017-09-26
  • 2014-01-31
  • 1970-01-01
相关资源
最近更新 更多