I have a text file (.txt) with the following two strings as so (this is a snippet of a larger file where all strings have the same format):
["('a', '1')", "('b', '2')"]
["('c', '3')", "('d', '4')"]
I am using the below code to parse the strings in the text file so that I can access each element for data analysis. The code works for the string if I declare it as a variable, such as:
string = ["('c', '3')", "('d', '4')"]
But the code does not work for the text file:
import ast
text_file = open('text_file.txt', 'r')
for string in text_file:
parsed = list([ast.literal_eval(x) for x in text_file])
print parsed
I would expect to get:
[('a', '1'), ('b', '2')]
[('c', '3'), ('d', '4')]
But I get the following error:
Traceback (most recent call last):
File "test.py", line 8, in <module>
parsed = list([ast.literal_eval(x) for x in string])
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
[
^
SyntaxError: unexpected EOF while parsing