我试图逐行读取以下数据,每行都是python词典格式:
的test.txt:
{u'FirstName': u'John', u'Title': u'Mr', u'LastName': u'Doe', u'LastSeenDate': datetime.datetime(2013, 11, 11, 0, 0)}
{u'FirstName': u'Mary', u'Title': u'Ms', u'LastName': u'Doe', u'LastSeenDate': datetime.datetime(2013, 11, 12, 0, 0)}
以下是代码和错误:
with open("test.txt", "r") as ins:
for line in ins:
data =ast.literal_eval(line)
print(data["Title"])
ValueError Traceback (most recent call last)
<ipython-input-27-d736d3d4199c> in <module>()
21
22 if __name__ == '__main__':
---> 23 main()
<ipython-input-27-d736d3d4199c> in main()
14 with open("test.txt", "r") as ins:
15 for line in ins:
---> 16 data =ast.literal_eval(line)
17 print(data["Title"])
18
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.pyc in literal_eval(node_or_string)
78 return left - right
79 raise ValueError('malformed string')
---> 80 return _convert(node_or_string)
81
82
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.pyc in _convert(node)
61 elif isinstance(node, Dict):
62 return dict((_convert(k), _convert(v)) for k, v
---> 63 in zip(node.keys, node.values))
64 elif isinstance(node, Name):
65 if node.id in _safe_names:
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.pyc in <genexpr>((k, v))
60 return list(map(_convert, node.elts))
61 elif isinstance(node, Dict):
---> 62 return dict((_convert(k), _convert(v)) for k, v
63 in zip(node.keys, node.values))
64 elif isinstance(node, Name):
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.pyc in _convert(node)
77 else:
78 return left - right
---> 79 raise ValueError('malformed string')
80 return _convert(node_or_string)
81
ValueError: malformed string
如何避免格式错误的字符串错误以及解析这些数据的正确方法是什么?
答案 0 :(得分:1)
我会使用pickle,因为它是您的数据,因此您应该能够信任它。
转储报告:
from pickle import dump # cPickle in case of Python2
with open('report.pickle', 'wb') as pickle_stream:
for row in generate_rows():
dump(row, pickle_stream, 2) # The version must be at least 1.
阅读报告:
from pickle import load # cPickle in case of Python2
with open('report.pickle', 'wb') as pickle_stream:
while True:
try:
row = load(pickle_stream)
except EOFError:
break
do_something_with(row)