所以我有一个txt文件,内容是这样的:
experiment_setup = {
"1": {
"FileName": "WT_L-1C.raw",
"Condition": "Exponential",
"Biorep": 1,
"Fraction": "Cytoplasm",
"Techrep": 1,
},
"2": {
"FileName": "WT_L-1M.raw",
"Condition": "Exponential",
"Biorep": 1,
"Fraction": "Membrane",
"Techrep": 1,
}
}
理想情况下,我想将该文件读入非常相似的字典中。但目前我的代码是这样的:
param_file = sys.argv[2]
# read param file as dictionary
param_dict = {}
file = open(param_file, 'r')
for line in file.readlines():
key, value = line.strip().split(":")
param_dict[key.strip()] = value.strip()
file.close()
基本上我以
"a" : "b"
的形式输入并放入字典中。如何在字典字典中读取字典文件的实验设置字典
您可以打开文件文件并阅读其全部内容。然后搜索第一次出现的左大括号。使用 ast.literal_eval 来解释内容。
from ast import literal_eval
with open('/Volumes/G-Drive/foo.txt') as data:
content = data.read()
if (offset := content.find('{')) >= 0:
param_dict = literal_eval(content[offset:])
print(param_dict)
输出:
{'1': {'FileName': 'WT_L-1C.raw', 'Condition': 'Exponential', 'Biorep': 1, 'Fraction': 'Cytoplasm', 'Techrep': 1}, '2': {'FileName': 'WT_L-1M.raw', 'Condition': 'Exponential', 'Biorep': 1, 'Fraction': 'Membrane', 'Techrep': 1}}