Thread: Storing data

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

    Join Date
    Sep 2013
    Posts
    12
    Rep Power
    0

    Storing data


    Before i ask my question, i want to thank all of you for some great help!

    My question is this: Can I make python store data (a number in my situation) in a text file and then read from it later for use and remanipulation?
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    620
    Rep Power
    65
    There are a number of ways ...
    Code:
    # with just a number as data use this ...
    data_num = 12345.678
    # write() needs a string
    data_str = str(data_num)
    file_name = "mynumber.txt"
    # write the string out, fh_out is the file handle
    with open(file_name, "w") as fh_out:
        fh_out.write(data_str)
    
    # read back in, fh_in is the file handle (mode "r" is default)
    with open(file_name) as fh_in:
        # read() returns a string, so convert with float()
        data_num2 = float(fh_in.read())
        
    # testing ...
    print(data_num, type(data_num))
    print(data_num, type(data_num2))
    
    ''' result ...
    12345.678 <class 'float'>
    12345.678 <class 'float'>
    '''
    Other object can be saved and read back in ...
    Code:
    ''' pickle104.py
    saving and loading data
    '''
    
    data_str = '''\
    fred
    karl
    rita'''
    
    # split at the newline char to form a list
    data_list = data_str.split('\n')
    
    # save the data_list object with module pickle
    import pickle
    
    # save/dump to the working directory or give full path name
    fname = "mylist.dat"
    # "wb" is binary write mode
    with open(fname, "wb") as fout:
        pickle.dump(data_list, fout)
        
    
    # load the list object back with pickle
    # "rb" is binary read mode
    with open(fname, "rb") as fin:
        data_list2 = pickle.load(fin)
    
    # testing ...
    print(data_list)
    print(data_list2)
    
    print('-'*25)
    
    # you could save the data string to a text file this way,
    # but then you have to use the split('\n') to a list again on loading
    fname2 = "mystring.txt"
    with open(fname2, "w") as fout:
        # write() needs a string variable
        fout.write(data_str)
    
    # read back in
    with open(fname2) as fin:
        # read() returns a string
        data_str2 = fin.read()
    
    # testing ...
    print(data_str)
    print('-'*5)
    print(data_str2)
    
    ''' result -->
    ['fred', 'karl', 'rita']
    ['fred', 'karl', 'rita']
    -------------------------
    fred
    karl
    rita
    -----
    fred
    karl
    rita
    '''
    Last edited by Dietrich; September 17th, 2013 at 02:12 PM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo