0

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. The Problem is not in reading file and assign values to variables but when TEXT is involved in the assignment and this was not discussed elsewhere.

import os
File_InputApi = "c:\temp\File_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()
hdsouza
  • 354
  • 4
  • 17
  • Briefly: make this input file valid Python and then simply import it. – TigerhawkT3 Sep 18 '21 at 16:54
  • 1
    @TigerhawkT3 that would be a massive security risk – Einliterflasche Sep 18 '21 at 16:55
  • @Einliterflasche - That's what OP is going for anyway. – TigerhawkT3 Sep 18 '21 at 16:55
  • 1
    I was about to propose https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-via-a-while-loop as a duplicate. – mkrieger1 Sep 18 '21 at 16:56
  • 1
    There are number of ways to read configuration [files] in python https://stackoverflow.com/q/19379120/4046632 and https://stackoverflow.com/q/5055042/4046632 – buran Sep 18 '21 at 16:56
  • @TigerhawkT3 How is reading strings from a file more insecure than importing it as python code? – Einliterflasche Sep 18 '21 at 16:57
  • @Einliterflasche - Look at what OP is doing: they're using `exec` to execute assignment statements. It fails because they're not enclosing in quotes what I assume was meant to be a string. The chances of this code being targeted for use in a production/online environment are nil, so the most straightforward way of accomplishing what OP wants is exactly what I said in the beginning. – TigerhawkT3 Sep 18 '21 at 16:59
  • The input file already works correctly. If it only contains "zip => 22101" there is no error (See question above). It appears that ONLY when I try to assign TEXT as the value of a VARIABLE it fails. But then again it is already specified as %s (meaning string) Also this is different from the other question on the forum. – hdsouza Sep 18 '21 at 18:49

0 Answers0