Putting a line from a text file into a variable, then moving to next line

Tim Chase python.list at tim.thechases.com
Sun Oct 7 08:18:20 EDT 2007


> I'm not really sure how readline() works. Is there a way to iterate 
> through a file with multiple lines and then putting each line in a 
> variable in a loop?

You can use readlines() to get the whole line (including the
newline):

  lines = file('x.txt').readlines()

or you can iterate over the file building a list without the newline:

  lines = [line.rstrip('\n') for line in file('x.txt')]

Thus, line[0] will be the first line in your file, line[1] will
be the second, etc.

-tkc







More information about the Python-list mailing list