How to write a list into a file?
Kluesi last edited by
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.
For debugging you can simply
reprto 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 the
jsonmodule to store your list as JSON. The basic JSON data types (
false, numbers, strings, arrays, objects) are very similar to some of Python's built-in types (
Webmaster4o last edited by
You could just use
@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 Python
eval, or if you're lucky
ast.literal_eval. Using the
jsonmodule 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)
Marque___ last edited by
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
;)This wasn't meant as a working script, I only wanted to point out the differences between using
jsonto store a
listin a file.