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

Say I have a list list = [1,2,3,4,5], and it changes during my program. How can I save it to a file so that the next time the program starts, I can access the list of changes in the form of a list?

I tried:

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

with open("file.txt", 'w') as f:
    for s in score:
        f.write(str(s) + '\n')

with open("file.txt", 'r') as f:
    score = [line.rstrip('\n') for line in f]


print(score)

But this leads to the fact that the items in the list are not integer strings.

+20
source share
6 answers

I decided that I did not want to use a pickle, because I wanted to be able to open a text file and easily change its contents during testing. So 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")

with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

, , , .

+16

pickle. :

  • (dump). Python .
  • Unpickling (load): .

https://docs.python.org/3.3/library/pickle.html :

>>> import pickle
>>> l = [1,2,3,4]
>>> with open("test.txt", "wb") as fp:   #Pickling
...   pickle.dump(l, fp)
... 
>>> with open("test.txt", "rb") as fp:   # Unpickling
...   b = pickle.load(fp)
... 
>>> b
[1, 2, 3, 4]
+47

pickle, , :

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 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'

+9

pickle . .py, .

>>> score = [1,2,3,4,5]
>>> 
>>> with open('file.py', 'w') as f:
...   f.write('score = %s' % score)
... 
>>> from file import score as my_list
>>> print(my_list)
[1, 2, 3, 4, 5]
+3

.

import pandas as pd
x = pd.Series([1,2,3,4,5])
x.to_excel('temp.xlsx')
y = list(pd.read_excel('temp.xlsx')[0])
print(y)

, .

0

, numpy save . ,

sampleList1=['z','x','a','b']
sampleList2=[[1,2],[4,5]]

, , .npy

def saveList(myList,filename):
    # the filename should mention the extension 'npy'
    np.save(filename,myList)
    print("Saved successfully!")

def loadList(filename):
    # the filename should mention the extension 'npy'
    tempNumpyArray=np.load(filename)
    return tempNumpyArray.tolist()

>>> saveList(sampleList1,'sampleList1.npy')
>>> Saved successfully!
>>> saveList(sampleList2,'sampleList2.npy')
>>> Saved successfully!

# loading the list now 
>>> loadedList1=loadList('sampleList1.npy')
>>> loadedList2=loadList('sampleList2.npy')

>>> loadedList1==sampleList1
>>> True

>>> print(loadedList1,sampleList1)

>>> ['z', 'x', 'a', 'b'] ['z', 'x', 'a', 'b']
0

Source: https://habr.com/ru/post/1569727/


All Articles