0

I'm writing a script that contains a large list. I'm trying to modify my script so that instead of needing to edit the script directly to add/remove items to this list, it reads lines from a text file. Is it possible to use variables inside of this data file?

For example, If my text file contains this:

thing
number+str(variable)

And my script looks like this:

import os

variable = '123456'
file = 'C:\whatever.txt'

#make the list 'commands'
with open(file) as f:
        commands = []
        for line in f:
                line = line.replace('\n','')
                commands.append(line)

#make the list 'oldcommands'
oldcommands = ['thing','number'+str(variable)]

print(commands)
print(oldcommands)

How do I get both of these outputs to be the same?

This is the result of running the script above:

['thing', 'number+str(variable)']
['thing', 'number123456']

Formatting the file in a particular way is not a problem, I'm just trying to make my script more modular/portable

  • 1
    Will your variables always be inside of a `str()`? – Samantha Jul 24 '19 at 21:56
  • They can be, yes – cbrianfoley Jul 24 '19 at 21:57
  • use can use `eval` on the strings – VersBersch Jul 24 '19 at 22:00
  • 1
    This feels like an [XY Problem](http://xyproblem.info/). Try to go one step back and explain your goal here. It sounds like there could be a better way of doing this – Tomerikoo Jul 24 '19 at 22:08
  • You may be right, that I'm asking too specific of a question. What I'm doing is piping these commands to putty using pywinauto and this snip of code ````for cmd in commands: putty.type_keys(cmd) putty.type_keys('{ENTER}') time.sleep(.3)```` The point is to try to prompt for variables ahead of time that will be used along the way – cbrianfoley Jul 25 '19 at 01:28
  • It sounds like you could use the `format`. As long as you know in advance what variables appear in your text file. `"variables = {"variable_1": value_1, "variable_2": value_2, ...}`. Then `for line in f: line.format(**variables)`. – Kyle Parsons Jul 25 '19 at 02:17

1 Answers1

0

Try this: (This should work for your case)

import os

variable = '123456'
file = 'C:\whatever.txt'

#make the list 'commands'
with open(file) as f:
        commands = []
        for line in f:
                line = line.replace('\n','')
                if '+' in line:
                   line = line.split('+')
                   line = line[0] + eval(line[1])
                commands.append(line)

#make the list 'oldcommands'
oldcommands = ['thing','number'+str(variable)]

print(commands)
print(oldcommands)
Nothing
  • 502
  • 3
  • 11