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

后端 未结 9 1045
既然无缘
既然无缘 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']
    
    0 讨论(0)
  • 2020-12-02 08:03

    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")
    
    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.

    0 讨论(0)
  • 2020-12-02 08:05

    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'

    0 讨论(0)
  • 2020-12-02 08:09

    You can use pickle module for that. This module have two methods,

    1. Pickling(dump): Convert Python objects into string representation.
    2. Unpickling(load): Retrieving original objects from stored string representstion.

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

    Code:

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

    Also Json

    1. dump/dumps: Serialize
    2. load/loads: Deserialize

    https://docs.python.org/3/library/json.html

    Code:

    >>> import json
    >>> with open("test.txt", "w") as fp:
    ...     json.dump(l, fp)
    ...
    >>> with open("test.txt", "r") as fp:
    ...     b = json.load(fp)
    ...
    >>> b
    [1, 2, 3, 4]
    
    0 讨论(0)
  • 2020-12-02 08:10

    Although the accepted answer works, you should really be using python's json module:

    import json
    
    score=[1,2,3,4,5]
    
    with open("file.json", 'w') as f:
        # indent=2 is not needed but makes the file 
        # human-readable for more complicated data
        json.dump(score, f, indent=2) 
    
    with open("file.json", 'r') as f:
        score = json.load(f)
    
    print(score)
    

    The main advantages of using a json are that:

    1. json is a widely adopted and standardized data format, so non-python programs can easily read and understand the data inside the json file.
    2. json files are human-readable.
    3. You can literally save any list/dictionary in python to a json (as long as all the contents are serializable, so most objects/functions can't be saved into a json without explicit conversion to a serializable object)

    The main disadvantages of using a json are that:

    1. The data is stored in plain-text, meaning the data is completely uncompressed, making it a slow and bloated option for large amounts of data. I wouldn't recommend storing gigabytes of vectors in a json format (hdf5 is a much better candidate for that).
    2. The contents of a list/dictionary need to be serializable (python objects need to be explicitly serialized when dumping, and then deserialized when loading).

    The json format is used for all kinds of purposes:

    • node.js uses it to track dependencies with package.json
    • many REST APIs use it to transmit and receive data
    • jsons are also a great way to store complicated nested lists/dictionaries (like an array of records).

    In general, if I want to store something I know I'm only ever going to use in the context of a python program, I typically go to pickle. If I need a platform agnostic solution, or I need to be able to inspect my data once it's stored, I go with json.

    0 讨论(0)
  • 2020-12-02 08:15
    errorlist = ['aaaa', 'bbbb', 'cccc', 'ffffdd']
    
    f = open("filee.txt", "w")
    f.writelines(nthstring + '\n' for nthstring in errorlist)
    
    f = open("filee.txt", "r")
    cont = f.read()
    contentlist = cont.split()
    print(contentlist)
    
    0 讨论(0)
提交回复
热议问题