How to Iterate over readlines() in python

joshlsullivan picture joshlsullivan · Jan 12, 2015 · Viewed 21.1k times · Source

I am trying to add lines from a txt file to a python list for iteration, and the script wants to print every line and return an error. I'm using the readlines() function, but when I use list.remove(lines), it returns an error: File "quotes.py", line 20, in main list.remove(lines) TypeError: remove() takes exactly one argument (0 given).

def main():
while True:
    try:
        text_file = open("childrens-catechism.txt", "r")
        lines = text_file.readlines()
        #    print lines
        #    print len(lines)
        if len(lines) > 0:
            print lines
            list.remove(lines)
            time.sleep(60)
        else:
            print "No more lines!"
        break
        text_file.close()

I can't see what I'm doing wrong. I know it has to do with list.remove(). Thank you in advance.

Answer

Stephen Lin picture Stephen Lin · Jan 12, 2015

You can write in this way. It will save you some time and give you more efficiency.

import time
def main():
    with open("childrens-catechism.txt", "r") as file:
        for line in file:
            print line,
            time.sleep(60)