Creating lists from text file

2019-06-09 09:28发布

问题:

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?

回答1:

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']


回答2:

  1. You are adding variables to the local namespace of the function. Nothing you add like that will be visible outside the function.
  2. The assignment you are making is to a variable named by 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:

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

The question you have to ask yourself is why you want to do that. Let's say you load your file:

with open("mydog.txt") as f:
    for line in f:
        createlist(line.strip())

Now indeed you can do

>>> print(bingo)
['test']

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:

with open("mydog.txt") as f:
    mylists = {line.strip(): ['test'] for line in f}

Now you can access the items by name:

>>> mylists['bingo']
['test']

But more importantly, you can check what names you got and actually manipulate them in a meaningful way:

>>> list(mylists.keys())
['bingo', 'bango', 'smelly', 'wongo']


回答3:

file = open("mydog.txt")
my_list =file.read().splitlines() # will create the list from the file which should contain only names without '\n'
file.close()

Or with block to not worry about file closing

with open("mydog.txt") as file:
    my_list =file.read().splitlines() # will create the list from the file which should contain only names without '\n'

In 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 string test

my_dict={i:['test'] for i in my_list}

Then try to print

print(my_dict['bingo']) # will print list ['test']

Printing entire dict

print(my_dict) 

Output:

{'bango': ['test'], 'bingo': ['test'], 'smelly': ['test'], 'wongo': ['test']}