Newbie question: Any way to improve this code?

Gary Herron gherron at islandtraining.com
Sat Dec 6 00:25:21 CET 2003


On Friday 05 December 2003 02:00 pm, 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 ()
> ... bunch of lines deleted ...


Instead of this and all the rest of the code, you can just
  frases = f.readlines()

Then 'frases' will be a list of strings, each string containing one line
from the file.  

If you want to see what you've got try

  print frases

You'll see that each string contains the newline the ended the line in
the file.  To get rid of them and any other beginning or ending white
space (if you want) do:
  
  for i in range(len(frases)):
    frase[i] = frase[i].strip()
    
If your file might contain empty lines, you can get rid of them with
either a standard loop

  final = []
  for phrase in frases:
    if phrase:
      final.append(phrase.strip())

Or, if you're adventurous for a beginner, try list comprehensions.

  final = [phrase.strip()   for phrase in frases   if phrase]


And finally, all this could be done in one line

  frases = [phrase.strip()   for phrase in f.readlines()   if phrase]

Gary Herron










More information about the Python-list mailing list