2

I have a program which outputs a list in a .txt file on a server and I want to save that list in a new variable.
I'm doing:

with open ("file.txt", "r") as myfile:
    data = myfile.read().replace('\n', '')
var = data

but obviously print(var) returns a string "[list, of, stuff]"

Yeah I can bypass the txt-save procedure but what in case I could not?

3

1 Answer 1

6

you can use AST

import ast
var="[list, of, stuff]"
var=ast.literal_eval(var)
print var[0]
#output list

From docs

ast.literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

If you're original data was serialized using JSON then you could also use the json module from the Python standard library.

Even if it was just print(some_list) you could still use the json library; i.e:

>>> from json import dumps, loads
>>> xs = [1, 2, 3]
>>> loads(dumps(xs)) == loads(repr(xs))
True
Sign up to request clarification or add additional context in comments.

1 Comment

ast.literal_eval() solved my problem perfectly. Thanks!

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.