Newbie question: Any way to improve this code?

Bengt Richter bokr at oz.net
Fri Dec 5 20:39:23 EST 2003


On Fri, 05 Dec 2003 23:45:04 GMT, "David M. Cook" <davecook at nowhere.net> wrote:

>In article <bqqvnl$kbo$1 at taurus.webcorp.pl>, Gustavo Campanelli wrote:
> 
>> 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 = ""
>
>f = open("firmas.txt",'r') # open the file
>frases = []
>for line in f.readlines():
>    frases.append(line[:-1])
>    
>line[:-1] is all but the last element of line.
>    
>or even
>
>frases = map(str.rstrip, f.readlines())
>
>although that may strip more of the end than you want.

Someone's working too hard ;-) Should work:

    frases = file('firmas.txt').read().splitlines()

Regards,
Bengt Richter




More information about the Python-list mailing list