Newbie question: Any way to improve this code?

Chris Lee cl at 127.0.0.1
Fri Dec 5 18:45:32 EST 2003


Gustavo Campanelli wrote:
> I'm begining to work in a program that cicles through a list of phrases 
> (basically, a changing signature file). I started yesterday, and I only 
> have abput 8 full hours of real Python experience.
> 
> So far I produced a code that succesfully reads an process the file, 
> separating the phrases. Is there any way to optimize this code, so that 
> I don't have to use the if for the first list member?
> 
> Now for the data.
> The file is firmas.txt, it contains the following three example phrases
> 
> Frase 1
> Frase 2
> Frase 3
> 
> Note that this phrases are separated by newline characters. Upon reading 
> the full file (it won't be long) I get this:
> 
> 'Frase 1\nFrase 2\nFrase 3\n'
> 
> so, as you can see, the newlines are there.
> 
> My code is this (I know I should close the file, but so far the runtime 
> is so small it doesn't really matter, that'll change)
> 
> import string
> f = open("firmas.txt",'r') # open the file
> texto = f.read ()
> n = range (len (texto))
> frases = [0]
> frase =""
> cant = 0
> for a in n:
>     if texto [a] != "\n":
>        frase = frase + (texto [a])
>     else:
>         if cant == 0:
>             frases [0] = frase
>         else:
>             frases.append (1)
>             frases [cant] = frase
>         cant +=1
>         frase = ""
> 
> Well, that's it, thanks.
> 
> Gustavo Campanelli
> 

Ok, so I'm probably talking too soon (...30 minutes of python learning) 
but python has a readline() function for the file object.

f = open("firmas.txt",'r') # open the file
texto=f.readline() #texto contains the first line

There is also a readlines() method (note the plural) which reads all of 
the lines in a file

f = open("firmas.txt",'r') # open the file
texto=f.readlines() #texto contains an list of all the lines

There is also (I'm learning quickly) the iterator method

f = open("firmas.txt",'r') # open the file
for line in f:
	print line #or whatever



...And I spent most of this week thinking the STL was cool.





More information about the Python-list mailing list