Variable + String Format

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Feb 9 09:34:14 EST 2009


En Tue, 10 Feb 2009 08:03:06 -0200, Joel Ross <joelc at cognyx.com> escribió:

> #########################################################################
>
> wordList = "/tmp/Wordlist"
> file = open(wordList, 'r+b')
>
>
> def readLines():
>
>          for line in file.read():
>              if not line: break
>              print line + '.com '
>              return line
>
>
>
> readLines()
> file.close()
>
> ##########################################################################
>
> It returns the results:
>
> t.com
>
> NOTE: Only returns the first letter of the first word on the first line  
> e.g. test would only print t and readline() does the same thing.

This should print every line in the file, adding .com at the end:

wordList = "/tmp/Wordlist"
with open(wordList, 'r') as wl:
   for line in wl:
     print line.rstrip() + '.com '

Note that:
- I iterate over the file self; files are their own line-iterators.
- I've used the 'r' mode instead (I assume it's a text file because you  
read it line by line, and as you don't update it, the '+' isn't required)
- the line read includes the end-of-line '\n' at the end; rstrip() removes  
it and any trailing whitespace. If you don't want this, use rstrip('\n')
- I've used the with statement to ensure the file is closed at the end


-- 
Gabriel Genellina




More information about the Python-list mailing list