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?

AMC
  • 2,642
  • 7
  • 13
  • 35

1 Answers1

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
James Mills
  • 18,669
  • 3
  • 49
  • 62
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46