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

Tim Williams tdwdotnet at gmail.com
Sun Oct 7 19:40:19 CEST 2007

On 07/10/2007, Tim Chase <python.list at tim.thechases.com> wrote:
> > 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.

or splitlines()
>>>  lines = open('x.txt').read().splitlines()


More information about the Python-list mailing list