如果你有在[1, 2, 3, 4]
形式的東西,在這種情況下,你可以使用ast
:
In [1]: import ast
In [2]: with open('lists.txt', 'rb') as f:
...: lists = f.readlines()
...:
...:
In [3]: list_container = [ast.literal_eval(line.strip()) for line in lists]
In [4]: list_container
Out[4]: [[1, 2, 3], [[1, 2, 3], [4, 5, 6]]]
在這種情況下,lists.txt
是這樣的:
[1, 2, 3]
[[1, 2, 3], [4, 5, 6]]
但是,如果你的文件看起來與上述狀態完全相同,您可以使用exec
,但應始終謹慎使用exec
和eval
之類的內容:
In [2]: with open('test.txt', 'rb') as f:
...: contents = f.read()
...:
...:
In [3]: exec(contents)
In [4]: mylist
Out[4]: [1, 2, 3, 4]
In [5]: myotherlist
Out[5]: [[1, 3, 4, 5], [3, 5, 3, 6]]
In [6]: print contents
mylist = [
1,
2,
3,
4]
myotherlist = [
[1, 3, 4, 5],
[3, 5, 3, 6]
]
文件是否有不可以人工編輯和/或人類可讀? – Wessie
是的。它需要是可編輯和可讀的。 – michael