Python - Storing Python Objects in Files

Description

Storing Python Objects in Files

Demo

X, Y, Z = 43, 44, 45                       # Native Python objects 
S = 'Test'                                 # Must be strings to store in file 
D = {'a': 1, 'b': 2} 
L = [1, 2, 3] # from w w w.j av  a2  s. co  m

F = open('datafile.txt', 'w')              # Create output text file 
F.write(S + '\n')                          # Terminate lines with \n 
F.write('%s,%s,%s\n' % (X, Y, Z))          # Convert numbers to strings 
F.write(str(L) + '$' + str(D) + '\n')      # Convert and separate with $ 
F.close() 

chars = open('datafile.txt').read()        # Raw string display 
print(chars)                               # User-friendly display

Result

Related Topic