0

I have a text file which looks something like this:

["someString",1234,True],["anotherString",5678,False]

I am trying to convert the content of the file to a list, like this:

[["someString",1234,True],["anotherString",5678,False]]

So I tried to do this with the following lines:

test = open('file.txt','r')
test = test.read()

But this converts it to a string, like this:

'["someString",1234,True],["anotherString",5678,False]'

How can I convert this to a list?

1 Answer 1

1

Wrap the string in brackets and use ast.literal_eval to parse it:

>>> from ast import literal_eval

>>> testString = '["someString",1234,True],["anotherString",5678,False]'

>>> literal_eval("[" + testString + "]")
[['someString', 1234, True], ['anotherString', 5678, False]]
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know why json.loads('[' + testString + ']') fails?
@Vlad False is not a JSON keyword; false is however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.