#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    6
    Rep Power
    0

    Question How to save and load lists?


    be warned, I am very new to python
    I'm having some trouble doing my Computing coursework because it requires me to save and load lists for my spelling challenge program. Basically, I need to learn how to save a list of 10 words so that it can be loaded into the program next time it is opened, rather than having to re-input words into the list every time it is opened. Can anyone help? I know this is probably quite simple, but I haven't seen any specific tutorials on how to do this on the internet thus far.

    Thanks
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,996
    Rep Power
    481
    You'll learn to spell the words better by re-keying them each time. None-the-less,
    Code:
    'copy data from one variable to another via pickling'
    
    import pickle
    
    PickleMeTink = list('pickle')
    
    with open('pickle', 'wb') as Pickle:
        pickle.dump(PickleMeTink, Pickle)
    
    with open('pickle', 'rb') as Pickle:
        pickel = pickle.load(Pickle)
    
    assert PickleMeTink == pickel
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    620
    Rep Power
    65
    Another way ...
    Code:
    mylist = [
    'car',
    'radio',
    'dog',
    'cat'
    ]
    
    # create a string of ';' separated words
    mystr = ";".join(word for word in mylist)
    
    fname = "mywords.txt"
    # write the string to file
    with open(fname, "w") as fout:
        fout.write(mystr)
        
    # read the string back in and convert to a list
    # by splitting the string at ';'
    with open(fname, "r") as fin:
        mylist2 = fin.read().split(';')
    
    print(mylist)
    print(mylist2)
    
    ''' result ...
    ['car', 'radio', 'dog', 'cat']
    ['car', 'radio', 'dog', 'cat']
    '''
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo