从文本文件创建列表 [英] Creating lists from text file

查看:110
本文介绍了从文本文件创建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建列表,但是在名为"mydog.txt"的外部文件中具有列表的名称.

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

该子例程应该使用一个名称(例如"bingo"),然后将其转换为一个列表,并在该列表中包含"test".

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.

我应该拥有的最终变量是"bingo = [" test],bango = [" test],smoryy = [" test],wongo = [" test]

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

最后要打印的是['test'],但该列表不存在.

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

为什么在子例程createlist内部但不在子例程外部时,它作为列表打印出来?

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

推荐答案

您可以使用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])

print (bingo, bango, smelly, wongo)

输出:

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

这篇关于从文本文件创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆