Text file reading input variables from txt file

Mr Dan :

I do have a text file in this format

instance_name = "small_instance_01_simple";
d = 2; 
r = 3;
SCj = [80 57]; 
Dk = [96 22 14];
Cjk = [[81 51 31]  [82 47 54]];

How can I get the value of those variables in my python code? I have tried more ways but it was unsuccessfully

adnanmuttaleb :

First let us import re and define our file-like object:

import re

s = StringIO("""
    instance_name = "small_instance_01_simple";

    d = 2;

    r = 3;

    SCj = [80 57];

    Dk = [96 22 14];

    Cjk = [[81 51 31] [82 47 54]];
""")

The parse_value function try to parse the expr as primitive, if it fails as sequences and finally as strings:

def parse_value(expr):
  try:
    return eval(expr)
  except:
    return eval(re.sub("\s+", ",", expr))
  else:
    return expr

The parse_line function parse each line and returns the varaible name and value, if any:

def parse_line(line):
    eq = line.find('=')
    if eq == -1: raise Exception()
    key = line[:eq].strip()
    value = line[eq+1:-2].strip()
    return key, parse_value(value)

Now let extract the variables:

vars = {}
for line in s.readlines():
  try:
    key, val = parse_line(line)
    vars[key] = val
  except:
      pass

Let check what what we have:

for key, value in vars.items():
  print(key, value, type(value))

Output:

instance_name small_instance_01_simple <class 'str'>
d 2 <class 'int'>
r 3 <class 'int'>
SCj [80, 57] <class 'list'>
Dk [96, 22, 14] <class 'list'>
Cjk [[81, 51, 31], [82, 47, 54]] <class 'list'>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26609&siteId=1