Search code examples
pythonexternal

Creating lists from text file


I want to create lists, but have the name of the lists in an external file called "mydog.txt".

mydog.txt:

bingo
bango
smelly
wongo

Here is my code that converts the text into list elements. I think it works but for some reason, the values are not saved after it's finished:

def createlist(nameoflist):
    nameoflist = ["test"]
    print(nameoflist)

file = open("mydog.txt")
for i in file.readlines():
    i= i.replace("\n", "")
    print(i) #making sure text is ready to be created into a list name
    createlist(i)
file.close()
print("FOR fuction complete")

print(bingo) # I try to print this but it does not exist, yet it has been printed in the function

The subroutine is supposed to take a name (let's say "bingo") and then turn it into a list and have "test" inside of that list.

The final variables i should have are "bingo = ["test"], bango = ["test"], smelly = ["test"], wongo = ["test"]

The final thing that should be printed is ['test'] but the list does not exist.

Why does it print out as a list when inside of the subroutine createlist but not outside the subroutine?


Solution

  • You may use exec:

    with open('mydog.txt') as f:
        list_names = [line.strip() for line in f]
    
    for name in list_names:
        exec('{} = ["test"]'.format(name))
    
    local = locals()
    for name in list_names:
        print ('list_name:', name, ', value:', local[name])
    

    or

    print (bingo, bango, smelly, wongo)
    

    output:

    list_name: bingo , value: ['test']
    list_name: bango , value: ['test']
    list_name: smelly , value: ['test']
    list_name: wongo , value: ['test']
    
    or 
    
    ['test'] ['test'] ['test'] ['test']