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?
You may use
exec
:or
output:
nameoflist
, not the string that it refers to.To get around that, you have to assign to the module namespace. This is actually not that difficult:
The question you have to ask yourself is why you want to do that. Let's say you load your file:
Now indeed you can do
However, the whole point of using a file is to have dynamic names. You don't know what names you will get up front, and once you stick them into the global namespace, you won't know which variables came from the file and which ones from elsewhere.
Keep in mind that the global namespace is just a fancy but regular dictionary. My recommendation is to hold the variables in your own dictionary, just for the purpose instead:
Now you can access the items by name:
But more importantly, you can check what names you got and actually manipulate them in a meaningful way:
Or
with
block to not worry about file closingIn case you want to create the lists named after the names present in the text files you really should be creating a
dict
with keys as the names and value as list containing stringtest
Then try to print
Printing entire dict
Output: