close

How to save a list to a file and read it as a list type?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to save a list to a file and read it as a list type in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to save a list to a file and read it as a list type?

  1. How to save a list to a file and read it as a list type?

    I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing.

  2. save a list to a file and read it as a list type

    I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing.

Method 1

I decided I didn’t want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:

score = [1,2,3,4,5]

with open("file.txt", "w") as f:
    for s in score:
        f.write(str(s) +"\n")
score = []
with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

So the items in the file are read as integers, despite being stored to the file as strings.

Method 2

If you don’t want to use pickle, you can store the list as text and then evaluate it:

data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
    file.write(str(data))

with open("test.txt", "r") as file:
    data2 = eval(file.readline())

# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))

[0, 1, 2, 3, 4, 5] class ‘list’ class ‘int’

[0, 1, 2, 3, 4, 5] class ‘list’ class ‘int’

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read