Variable + String Format

Chris Rebert clp2 at rebertia.com
Mon Feb 9 05:13:00 EST 2009


On Tue, Feb 10, 2009 at 2:03 AM, Joel Ross <joelc at cognyx.com> wrote:
> Hi all,
>
> I have this piece of code:
> #########################################################################
>
> wordList = "/tmp/Wordlist"
> file = open(wordList, 'r+b')

Why are you opening the file in binary mode? It's content is text!

>
> def readLines():
>
>        for line in file.read():

.read() reads the *entire* file into a string. When you iterate over a
string, such as in a for-loop, you get *individual characters*,
whereas you appear to want lines of text. To go line-by-line, use `for
line in file` instead (note: `line` will include the trailing newline
at the end of each line).
And don't use `file` as a variable name; it shadows the name of the
buitlin type.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list