簡體   English   中英

從文件中讀取字典

[英]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]})

以及(所有步驟時間)的全局變量:

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]})})

如果視覺上不愉快,則非常易於使用! 我使用以下命令將此數組打印在此文件中:

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

我試圖遵循在這篇文章中找到的解決方案,但是當我嘗試讀取文件時,將值存儲在新的字典中

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)的解決方案

使用貨架創建數據庫。 這是一種簡便快捷的方法。 以下代碼幫助我創建了db:

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

更多信息在這里

如果您可以使用書架 (我認為您會這樣做 ,因為它是標准庫的一部分),我強烈建議您使用它。 使用擱架是一種存儲和加載python對象的簡便方法,而無需手動解析和重建它們。

import shelve

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

多數民眾贊成在存儲數據。 然后,當您需要檢索它時...

import shelve

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

就這么簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM