Python : Read file and assign values to variables [duplicate]

  python

I have an input TEXT file that I need to read and assign the values to variables.
Here is the contents of the text file:

zip => 22101
name => tom

The script is able to successfully assign for the first line and if I do a print(zip) it correctly returns 22101, but it fails on the second line with the error "NameError: name ‘tom’ is not defined". It fails on the exec line

import os
File_InputApi = "c:tempFile_InputApi.txt"
Handle_InputApi = open(File_InputApi, 'r')
for Line_InputApi in Handle_InputApi:
    var_InputApi = Line_InputApi.split('=>')[0].strip()
    val_InputApi = Line_InputApi.split('=>')[1].strip()
    exec("%s = %s" % (var_InputApi,val_InputApi))
    print(zip)  
Handle_InputApi.close()

Source: Python Questions

LEAVE A COMMENT