swe15
swe15

Reputation: 3

Dynamic variable python in a loop

I was looking through many posts here for a solution but maybe I was searching for the wrong phrase. I'm new to Python, my code problem is the following:

from yahoo_finance import Share
for line in open('fcts.txt'):
   yahoo = Share('YHOO')
   print (yahoo +'.' + line)

it should basically do the following but for every function inside fcts.txt:

from yahoo_finance import Share
yahoo = Share('YHOO')
print (yahoo.get_open())

while fcts.txt contains different functions like

get_open()
get_change()
...

Upvotes: 0

Views: 348

Answers (1)

Alfe
Alfe

Reputation: 59426

You can access methods by name like this:

from yahoo_finance import Share

with open('fcts.txt') as methodsFile:
  for methodName in methodsFile:
    yahoo = Share('YHOO')
    method = getattr(yahoo, methodName.strip())
    print (method())

But it looks rather crude to me.

Upvotes: 1

Related Questions