you can take it apart and store it delimited with spaces and then put it back together when reading it like so:
list1 = [12, 32, 233]
list2 = [345, 823, 209]
with open("textfile.txt", "w") as f:
for lst in [list1,list2]:
f.write(" ".join([str(i) for i in lst]) + "\n")
with open("textfile.txt", "r") as data:
data = [i.strip() for i in data.readlines()]
x = [[int(num) for num in i.split()] for i in data]
print(x)
[[12, 32, 233], [345, 823, 209]]
So what's going on?
well let's break it down into 2 steps; storing the values and retrieving the values
part 1
with open("textfile.txt", "w") as f:
for lst in [list1,list2]:
f.write(" ".join([str(i) for i in lst]) + "\n")
all this does is store the list separated by spaces
Using the join
function we can easily accomplish this with one workaround; since the values stored inside the list are integers they must be strings when used with this function. Hence the use of the following list comprehension: [str(i) for i in lst]
!
With that string, we can finally add a newline character to make sure we don't have one line of everything combined!
part 2
with open("textfile.txt", "r") as data:
data = [i.strip() for i in data.readlines()]
x = [[int(num) for num in i.split()] for i in data]
This is a little bit more complicated, in essence, this creates a list of the lines of the text file, and then strips them of newline characters.
From this, we split
each line by spaces, and then cast each string to an integer value inside our newly created list.