Python 将文本文件作为列表导入以进行迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22677853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:23:40  来源:igfitidea点击:

Python Import Text FIle as List to Iterate

pythonlistimporttext-files

提问by Ivan Vegner

I have a text file I want to import as a list to use in this for-while loop:

我有一个文本文件,我想将其作为列表导入以在此 for-while 循环中使用:

text_file = open("/Users/abc/test.txt", "r")
list1 = text_file.readlines
list2=[]
    for item in list1:
        number=0
        while number < 5:
            list2.append(str(item)+str(number))
            number = number + 1
    print list2

But when I run this, it outputs:

但是当我运行它时,它输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not iterable

What do I do?

我该怎么办?

采纳答案by alecxe

readlines()is a method, call it:

readlines()是一个方法,调用它:

list1 = text_file.readlines()

Also, instead of loading the whole file into a python list, iterate over the file object line by line. And use with context manager:

此外,不是将整个文件加载到 python 列表中,而是逐行迭代文件对象。并与上下文管理器一起使用

with open("/Users/abc/test.txt", "r") as f:
    list2 = []
    for item in f:
        number = 0
        while number < 5:
            list2.append(item + str(number))
            number += 1
    print list2

Also note that you don't need to call str()on itemand you can use +=for incrementing the number.

另请注意,您不需要调用str()item并且可以+=用于增加number.

Also, you can simplify the code even more and use a list comprehensionwith nested loops:

此外,您可以进一步简化代码并使用嵌套循环的列表理解

with open("/Users/abc/test.txt", "r") as f:
    print [item.strip() + str(number) 
           for item in f 
           for number in xrange(5)]

Hope that helps.

希望有帮助。

回答by Stefan Gruenwald

List comprehension comes to your help:

列表理解对您有所帮助:

print [y[1]+str(y[0]) for y in list(enumerate([x.strip() for x in open("/Users/abc/test.txt","r")]))]