简体   繁体   English

Python导入文本文件作为要迭代的列表

[英]Python Import Text FIle as List to Iterate

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? 我该怎么办?

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. 另外,不要将整个文件加载到python列表中,而是逐行遍历文件对象。 And use with context manager : 与上下文管理器一起使用

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 item and you can use += for incrementing the number . 还要注意,您不需要在item上调用str() ,并且可以使用+=来增加number

Also, you can simplify the code even more and use a list comprehension with 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. 希望能有所帮助。

列表理解可以为您提供帮助:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM