Newby: how to transform text into lines of text

Tim Chase python.list at tim.thechases.com
Sun Jan 25 08:54:13 EST 2009


> The idiomatic way would be iterating over the file-object itself - which 
> will get you the lines:
> 
> with open("foo.txt") as inf:
>      for line in inf:
>          print line

In versions of Python before the "with" was introduced (as in the 
2.4 installations I've got at both home and work), this can simply be

   for line in open("foo.txt"):
     print line

If you are processing lots of files, you can use

   f = open("foo.txt")
   for line in f:
     print line
   f.close()

One other caveat here, "line" contains the newline at the end, so 
you might have

  print line.rstrip('\r\n')

to remove them.


> content = a.read()
> for line in content.split("\n"):
>      print line

Strings have a "splitlines()" method for this purpose:

   content = a.read()
   for line in content.splitlines():
     print line

-tkc






More information about the Python-list mailing list