Putting a line from a text file into a variable, then moving to next line
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
> 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 will be the first line in your file, line will
> be the second, etc.
>>> lines = open('x.txt').read().splitlines()
More information about the Python-list