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

后端 未结 9 1083
既然无缘
既然无缘 2020-12-02 07:43

Say I have the list score=[1,2,3,4,5] and it gets changed whilst my program is running. How could I save it to a file so that next time the program is run I can access the c

9条回答
  •  醉话见心
    2020-12-02 08:02

    If you want you can use numpy's save function to save the list as file. Say you have two lists

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

    here's the function to save the list as file, remember you need to keep the extension .npy

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

    and here's the function to load the file into a list

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

    a working example

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

提交回复
热议问题