0

I am experimenting with calling functions using dictionary keys. At the moment there is only one function in the dictionary but I plan to add more. The code below works to display the list because the function 'loadlist' has no arguments and I have written 'gameone.txt' into the body code when opening the file as f.

I want to have the file name as an argument of the loadlist function so that the user types for example... loadlist('gameone.txt') or loadlist('gametwo.txt') etc depending on what they want to have displayed.

def interact():

command = raw_input('Command:')

def loadlist():

    with open('gameone.txt', 'r') as f:
        for line in f:
            print line


dict = {'loadlist': loadlist}
dict.get(command)()

return interact()

interact()

I have tried the code below but I cannot solve my problem.

def interact():

command = raw_input('Command:')

def loadlist(list):

    with open(list, 'r') as f:
        for line in f:
            print line


dict = {'loadlist': loadlist}
dict.get(command)()

return interact()

interact()

Thanks for any input.

nobody
  • 19,814
  • 17
  • 56
  • 77
dave_m
  • 23
  • 4
  • Here is a great post with some quality answers on stackoverflow that might help: http://stackoverflow.com/questions/817087/call-a-function-with-argument-list-in-python – Nathaniel Payne Apr 05 '14 at 07:47
  • just a note, you shouldn't use variable names that shadow built-in types (i.e. list, dict) – acushner May 23 '14 at 16:19

1 Answers1

0

You can try using *args.

def interact():

    command,file_to_load = raw_input('Command:').split(' ')

    # *args means take the parameters passed in and put them in a list called args
    def loadlist(*args):

        # get the argument from args list
        filename = args[0]

        with open(filename, 'r') as f:
            for line in f:
                print line


    dict = {'loadlist': loadlist}
    dict.get(command)(file_to_load)

interact()
Genome
  • 1,106
  • 8
  • 10