【发布时间】:2017-04-14 01:32:26
【问题描述】:
这不是重复的问题。我环顾四周,发现this question,但savez 和pickle 实用程序使文件无法被人类读取。我想将它保存在一个 .txt 文件中,该文件可以加载回 python 脚本。所以我想知道python中是否有一些实用程序可以促进这项任务并保持书面文件可供人类阅读。
numpy 数组字典包含二维数组。
编辑:
根据Craig's answer,我尝试了以下方法:
import numpy as np
W = np.arange(10).reshape(2,5)
b = np.arange(12).reshape(3,4)
d = {'W':W, 'b':b}
with open('out.txt', 'w') as outfile:
outfile.write(repr(d))
f = open('out.txt', 'r')
d = eval(f.readline())
print(d)
这给出了以下错误:SyntaxError: unexpected EOF while parsing。
但是out.txt确实包含预期的字典。如何正确加载?
编辑 2:
遇到一个问题:如果大小很大,克雷格的答案会截断数组。 out.txt 显示前几个元素,用... 替换中间元素并显示最后几个元素。
【问题讨论】:
-
为什么不把字典变成
pandas数据框,然后另存为pickle? -
pickle不会让写出来的内容不可读吗?
-
什么无法读取?
-
@splinter - 人类无法阅读。
-
为什么不
json?
标签: python arrays numpy dictionary