Python - Convert Text File Content to Python object

Description

Convert Text File Content to Python object

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] #   ww w  .ja  v  a 2s .c  o 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() 



F = open('datafile.txt')   # Open again 
line = F.readline()        # Next line from file 
line = F.readline() 
print( line )

parts = line.split('$')                    # Split (parse) on $ 
print( parts )
print( eval(parts[0]) )                             # Convert to any object type 
objects = [eval(P) for P in parts]         # Do same for all in list 
print( objects )

Result

Related Topic