Newby: how to transform text into lines of text

vsoler vicente.soler at gmail.com
Sun Jan 25 09:04:41 EST 2009


On 25 ene, 14:36, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> vsoler schrieb:
>
> > Hello,
>
> > I'va read a text file into variable "a"
>
> >      a=open('FicheroTexto.txt','r')
> >      a.read()
>
> > "a" contains all the lines of the text separated by '\n' characters.
>
> No, it doesn't. "a.read()" *returns* the contents, but you don't assign
> it, so it is discarded.
>
> > Now, I want to work with each line separately, without the '\n'
> > character.
>
> > How can I get variable "b" as a list of such lines?
>
> 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
>
> The advantage is that this works even for large files that otherwise
> won't fit into memory. Your approach of reading the full contents can be
> used like this:
>
> content = a.read()
> for line in content.split("\n"):
>      print line
>
> Diez

Thanks a lot. Very quick and clear



More information about the Python-list mailing list