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:

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?

1

2 Answers

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.

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")]))]

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like