从文件 python 中检索列表类型的多个词典
retrieving multiple dictionaries in list type from file python
我想在将列表传递到文件后检索该列表的字典。但是当我把它写在文本中时,我丢失了列表内容的格式。我怎样才能再次恢复以字典类型格式化的数据?
首先我创建了一个二维列表。然后我用空字典和有值的字典填值
dataValue = {
'telefone': '6298855663311',
'nome': '',
'pagamento': 'Boleto',
'embarque': '16:00'
}
emptyDi = {}
assentosMatriz2D = [
[dataValue, emptyDi, emptyDi, emptyDi, emptyDi],
[emptyDi, emptyDi, emptyDi, emptyDi, emptyDi],
[emptyDi, emptyDi, dataValue, emptyDi, emptyDi]
]
print(assentosMatriz2D[0][1])
with open('listfile.txt', 'w') as f:
f.writelines("%s\n" % place for place in assentosMatriz2D)
# define empty list
linhas = []
# open file and read the content in a list
with open('listfile.txt', 'r') as f:
filecontents = f.readlines()
for line in filecontents:
# remove linebreak which is the last character of the string
current_place = line[:-1]
# add item to the list
linhas.append(current_place)
create_lt = linhas[1]
print(create_lt[0][0])
print(f'the firt line {create_lt}')
output:::::
>>{}
>>[
>>the firt line [{}, {}, {}, {}, {}]
要检索作为字符串传递的字典,您可以使用 eval
(current_place = eval(line[:-1])
) 但因为它可以 运行 编码,所以非常不安全,如果您不这样做,请不要这样做不要相信消息来源。最常见的存储方式是 json
import json
with open('listfile.txt', 'w') as f:
json.dump(assentosMatriz2D, f)
# open file and read the content in a list
with open('listfile.txt', 'r') as f:
assentosMatriz2D = json.load(f)
我想在将列表传递到文件后检索该列表的字典。但是当我把它写在文本中时,我丢失了列表内容的格式。我怎样才能再次恢复以字典类型格式化的数据?
首先我创建了一个二维列表。然后我用空字典和有值的字典填值
dataValue = {
'telefone': '6298855663311',
'nome': '',
'pagamento': 'Boleto',
'embarque': '16:00'
}
emptyDi = {}
assentosMatriz2D = [
[dataValue, emptyDi, emptyDi, emptyDi, emptyDi],
[emptyDi, emptyDi, emptyDi, emptyDi, emptyDi],
[emptyDi, emptyDi, dataValue, emptyDi, emptyDi]
]
print(assentosMatriz2D[0][1])
with open('listfile.txt', 'w') as f:
f.writelines("%s\n" % place for place in assentosMatriz2D)
# define empty list
linhas = []
# open file and read the content in a list
with open('listfile.txt', 'r') as f:
filecontents = f.readlines()
for line in filecontents:
# remove linebreak which is the last character of the string
current_place = line[:-1]
# add item to the list
linhas.append(current_place)
create_lt = linhas[1]
print(create_lt[0][0])
print(f'the firt line {create_lt}')
output:::::
>>{}
>>[
>>the firt line [{}, {}, {}, {}, {}]
要检索作为字符串传递的字典,您可以使用 eval
(current_place = eval(line[:-1])
) 但因为它可以 运行 编码,所以非常不安全,如果您不这样做,请不要这样做不要相信消息来源。最常见的存储方式是 json
import json
with open('listfile.txt', 'w') as f:
json.dump(assentosMatriz2D, f)
# open file and read the content in a list
with open('listfile.txt', 'r') as f:
assentosMatriz2D = json.load(f)