Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
How to write a list into a file?
-
Hi
I have something like
x = [ [1, 2, 'Car'], [ [3, 4, 'House'], ... ]
Is there an easy way to write it to a file and read it from a file? E.g. something like
x.tostring() = ' [ [1, 2, 'Car'], [ [3, 4, 'House'], ... ]'
or something else.
Thanks Jens
-
For debugging you can simply
print
the list, which usesrepr
to convert it to a string. This is however not a good way to write a list to a file so you can load it again. For that you should use thejson
module to store your list as JSON. The basic JSON data types (null
,true
,false
, numbers, strings, arrays, objects) are very similar to some of Python's built-in types (None
,True
,False
,int
/float
,str
/unicode
,list
,dict
). -
You could just use
str(x)
. -
@Webmaster4o That does the same thing as
repr
. The issue with that is that the only way to parse such a string back into a Pythonlist
is usingeval
, or if you're luckyast.literal_eval
. Using thejson
module is not much more complicated. Compare:# Without JSON import ast # Store with open("myfile.txt", "w") as f: f.write(repr(mylist)) # Load with open("myfile.txt", "r") as f: mylist = ast.literal_eval(f.read())
# With JSON import json # Store with open("myfile.json", "w") as f: json.dump(mylist, f) # Load with open("myfile.json", "r") as f: mylist = json.load(f)
-
This script CANT be run on IOS, right?
-
Of course not, you can't run it on a PC either, because I never assigned anything to
mylist
.;)
This wasn't meant as a working script, I only wanted to point out the differences between usingrepr
/eval
andjson
to store alist
in a file.