【问题标题】:Combining Dictionary and writing into a text file and reading again as dictionary?结合字典并写入文本文件并再次作为字典读取?
【发布时间】:2017-10-19 22:34:26
【问题描述】:

我点击了一个链接,每次点击都会获得一个 json 文件。然后我将数据写入文本文件。但是当我想再次阅读时,我想将其作为字典阅读。我该怎么做。

def url_seq(limit=5):
    for i in range(limit):
        link = 'http:...x={}'.format(i)
    yield link

def json_seq(link):
    for text in link:
        with urllib.request.urlopen(text) as url:
            data = json.loads(url.read().decode())
            yield data['data']

open('data.txt', 'w').close()
for item in json_seq(url_seq(limit=100)):
        with open('data.txt', 'a') as f:
            json.dump(item, f)
            f.write(',')

输出文件是这样的, {'x': 0.0, 'y': -7.462079426179981},{'x': 1.0, 'y':-5.300602624446985},{'x': 2.0, 'y': 1.4418651159990272}, ... ,

但我想把它当作字典来读。这样我就可以将它们放入 pandas 数据框进行分析。

下面的代码给了我一个列表,有没有办法把它读到字典里。我对 Python 有点陌生,对不起,如果我的意思是一些非 Python 的东西。提前致谢。

f = open('data.txt', 'r')
lines = f.read().split(',')

【问题讨论】:

  • 如果保存为JSON,可以加载为JSON。

标签: json python-3.x dictionary


【解决方案1】:

我建议将所有单独的数据项放在一个列表中,并将 那个 保存为 JSON 文件。

data = [x for x in json_seq(url_seq(limit=100))]
with open('data.json', 'w') as f:
    json.dump(data, f)

稍后,您可以使用 pd.read_json 读取 JSON 文件:

df = pd.read_json('data.json')

如果您真的想节省内存,请在 item 写入之间添加左大括号和右大括号。

with open('data.json', 'w') as f:
    f.write('[')
    for item in json_seq(url_seq(limit=100)):
        f.write(json.dumps(item) + ',')
    f.write(']')

【讨论】:

  • 其实我是想节省内存,不想先把数据保存到列表中,而是直接把数据保存到文本文件中,因为数据会很大。
  • @DataPoliceInc.见编辑。另外,如果您打算将其作为 pandas 数据框读取,则可以将其编写为单个 JSON,我不知道会出现什么问题。
  • @COLDSPEED 现在我明白了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 2017-03-26
  • 2018-03-19
  • 1970-01-01
  • 2017-11-28
相关资源
最近更新 更多