从python中的单独文件导入列表变量

时间:2015-03-25 21:36:17

标签: python

script.py

list = ['one',
        'two',
        'three']
# python script here

我的列表变得非常长(约400行)...有没有办法将变量list放在一个单独的py文件中并导入它?

或者我应该有单独的文件并通过迭代创建一个列表?

LIST.TXT

one
two
three

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:2)

是的!只需创建另一个python列表并将其导入主程序。

变量.py

中的

mylist = ['this', 'that', 'theother']
在main.py中

from variables import mylist

答案 1 :(得分:2)

我会在这里使用pickle

try: 
    import cPickle as pickle
except ImportError:
    import pickle

my_list = ['one',
        'two',
        'three']

pickle.dump(my_list, open('my_list.pkl', 'wb')) 

my_list = pickle.load(open('my_list.pkl', 'rb'))

答案 2 :(得分:1)

为什么不呢?

vars.py

mylist = [
'one',
'two',
'three',
'four',
]

main.py

from vars import mylist

答案 3 :(得分:1)

Shashank和Justin提供了很好的答案但是如果你真的想把它保存为文本文件,你可能想尝试一下:

myfile = open('listFile.txt', 'r') for word in myfile: list.append(word)