从文件中读取字典

Read dictionary from file

背景(可选)

我正在编写一个 python 脚本来分析 Abaqus(有限元软件)输出。该软件生成具有专有格式的“.odb”。但是,由于 Dassault(Abaqus 软件的所有者)专门开发的 python 库,您可以访问存储在数据库中的数据。 python 脚本必须由软件 运行 才能访问这些库:

abaqus python myScript.py

但是这样使用新的库真的很难,我不能运行 matplotlib 库。所以我想导出我在文件中创建的数组,稍后使用不需要 运行 使用 abaqus

的其他脚本访问它

问题

为了操作数据,我使用了集合。例如:

coord2s11=defaultdict(list)

此数组存储一组节点的 Z 坐标及其应力值,在每个时间步:

coord2s11[time_step][node_number][0]=z_coordinate
coord2s11[time_step][node_number][1]=stress_value

对于给定的时间步长,输出将是:

defaultdict(<type 'list'>, {52101: [-61.83229635920749, 0.31428813934326172], 52102: [-51.948098314163417, 0.31094224750995636],[...], 52152: [440.18335942363655, -0.11255115270614624]})

和 glob(对于所有步骤时间):

defaultdict(<type 'list'>, {0.0: defaultdict(<type 'list'>, {52101: [0.0, 0.0],[...]}), 12.660835266113281: defaultdict(<type 'list'>, {52101: [0.0, 0.0],[...],52152: [497.74876378582229, -0.24295337498188019]})})

如果视觉上不愉快,还是比较好用的!我使用以下方法在 this file 中打印了这个数组:

with open('node2coord.dat','w') as f :
    f.write(str(glob))

我尝试遵循我找到的解决方案 on this post,但是当我尝试读取文件时,将值存储在新字典中

import ast

with open('node2coord.dat', 'r') as f:
    s = f.read()
    node2coord = ast.literal_eval(s)

我最后得到一个 SyntaxError: invalid syntax,我猜它来自数组中的 defaultdict(<type 'list'>

有没有办法将数据存储在文件中,或者我应该修改它在文件中的写入方式吗?理想情况下,我想创建与我存储的完全相同的数组。

Joel Johnson 的解决方案

正在使用 shelve 创建数据库。这是一种简单快捷的方法。以下代码帮我创建了数据库:

import os
import shelve

curdir = os.path.dirname(__file__) #defining current directory

d = shelve.open(os.path.join(curdir, 'nameOfTheDataBase')) #creation of the db
d['keyLabel'] = glob # storing the dictionary in "d" under the key 'keyLabel'
d.close() # close the db

"with" 语句对我不起作用。 然后再打开它:

import os
import shelve


curdir = os.path.dirname(__file__)
d = shelve.open(os.path.join(curdir, 'nameOfTheDataBase')) #opening the db
newDictionary = d['keyLabel'] #loading the dictionary inside of newDictionary
d.close()

如果您收到错误提示

ImportError: No module named gdbm

只需安装 gdbm 模块。对于 linux :

sudo apt-get install python-gdbm

更多信息here

如果您可以访问 shelve(我认为您可以访问,因为它是标准库的一部分),我强烈建议您使用它。使用搁置是一种存储和加载 python 对象的简单方法,无需手动解析和重建它们。

import shelve

with shelve.open('myData') as s:
    s["glob"] = glob

这就是用于存储数据的。然后当你需要取回它时...

import shelve

with shelve.open('myData') as s:
   glob = s["glob"]

就这么简单。