【问题标题】:Python: How to read the list from the text filePython:如何从文本文件中读取列表
【发布时间】:2013-12-18 23:57:05
【问题描述】:

我有一个包含列表的 python 文件。

localhost tmp]$ cat 1.txt 
['aaaaaaa','bbbbbbb','cccccc','dddddddd']

我想读取列表中的每个元素。我得到了每个角色。 如果列表变量声明为列表变量,我可以读取列表的每个值,但我的列表位于文本文件中。

#!/usr/bin/python
def get_vminfo(vms):
    for vm in vms:
        print vm

#vms=['aaaaaaa','bbbbbbb','cccccc','dddddddd']
with open('1.txt','r') as input:
    vms=input.read()

get_vminfo(vms)    

如何打印每个列表值???

【问题讨论】:

  • 你见过answer 和泡菜吗

标签: python-2.7


【解决方案1】:

这适用于较小的文件。请记住,数据存储在计算机的内存中,因为它构建了一个数据数组,因此如果您正在处理大文件,最好使用迭代器而不是这种方法。

遗憾的是,在迭代器中,您无法访问已读取的数据。

【讨论】:

  • 这里有问题的答案吗?
【解决方案2】:

使用ast.literal_eval:

>>> import ast
>>> with open('1.txt') as f:
...     ast.literal_eval(f.read())
... 
['aaaaaaa', 'bbbbbbb', 'cccccc', 'dddddddd']

>>> with open('1.txt') as f:
...     for x in ast.literal_eval(f.read()):
...         print x
... 
aaaaaaa
bbbbbbb
cccccc
dddddddd

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2017-08-29
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多