Newby: how to transform text into lines of text

Diez B. Roggisch deets at nospam.web.de
Sun Jan 25 08:36:15 EST 2009


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



More information about the Python-list mailing list