Question

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

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?

Was it helpful?

Solution

readlines() is a method, call it:

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:

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.

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.

OTHER TIPS

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")]))]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top