[英]Read lines from a text file containing dictionaries into elements of list
I have a text file that looks like this我有一个看起来像这样的文本文件
{'tableName': 'customer', 'type': 'VIEW'}
{'tableName': 'supplier', 'type': 'TABLE'}
{'tableName': 'owner', 'type': 'VIEW'}
I want to read it into a python program that stores it into a list of dictonaries like this我想将其读入 python 程序,该程序将其存储到这样的字典列表中
expectedOutput=[{'tableName': 'customer', 'type': 'VIEW'},{'tableName': 'supplier', 'type': 'TABLE'},{'tableName': 'owner', 'type': 'VIEW'}]
But the output I get is a list of strings但是我得到的 output 是一个字符串列表
output = ["{'tableName': 'customer', 'type': 'VIEW'}",
"{'tableName': 'supplier', 'type': 'TABLE'}",
"{'tableName': 'owner', 'type': 'VIEW'}"]
The code I run is我运行的代码是
my_file3 = open("textFiles/python.txt", "r")
data3 = my_file3.read()
output = data3.split("\n")
Can someone show me how do I store the entries inside the list as dicts and not strings.有人可以告诉我如何将列表中的条目存储为字典而不是字符串。 Thank you
谢谢
You can use eval
but it can be dangerous (only do this if you trust the file):您可以使用
eval
但它可能很危险(只有在您信任该文件时才这样做):
my_file3 = open("textFiles/python.txt") # specifying 'r' is unnecessary
data3 = my_file3.read()
output = [eval(line) for line in data3.splitlines()] # use splitlines() rather than split('\n')
If the file contains something like __import__('shutil').rmtree('/')
it could be very dangerous.如果文件包含类似
__import__('shutil').rmtree('/')
内容,则可能非常危险。 Read the documentation for eval
here在此处阅读
eval
的文档
If you don't fully trust the file, use ast.literal_eval
:如果您不完全信任该文件,请使用
ast.literal_eval
:
import ast
my_file3 = open("textFiles/python.txt")
data3 = my_file3.read()
output = [ast.literal_eval(line) for line in data3.splitlines()]
This removes the risk - if the file contains something like an import, it will raise a ValueError: malformed node or string
.这消除了风险 - 如果文件包含类似导入的内容,它将引发
ValueError: malformed node or string
。 Read the documentation for ast.literal_eval
here在此处阅读
ast.literal_eval
的文档
Output: Output:
[{'tableName': 'customer', 'type': 'VIEW'},
{'tableName': 'supplier', 'type': 'TABLE'},
{'tableName': 'owner', 'type': 'VIEW'}]
You can use the json
module您可以使用
json
模块
import json
my_file3 = open("textFiles/python.txt", "r")
data3 = my_file3.read()
output = json.loads(str(data3.splitlines()))
print(output)
As Thonnu warned, eval
is quite dangerous正如 Thonnu 警告的那样,
eval
非常危险
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.