I have been scanning the internet searching for the best way to read a string list in a file.
When writing to a file it gives me an error: TypeError: write() argument must be str, not list
So I made the list a string file.write(str([1,2,3]))
. So now in the file we have a string in the shape of a list so when reading this we will get [1, 2, 3]Note: This is a string not a list so we cannot acmes the elements. So I was wondering what would be the best way to read this line in the file as a LIST.
Using list(file.readline)
I get something like ['[', '1', ',', ' ', '2', ',', ' ', '3', ']']
Thats not what I want
so I try splitting at the comma: print(line.split(','))
I get: ['[1', ' 2', ' 3]']
I could iterate through the first element in the list and the last and get rid of the brackets. But I don't think that is the best idea.
Does anyone know a better way of reading a str(list) in a file as a list?