Variable + String Format

John Machin sjmachin at lexicon.net
Mon Feb 9 05:47:03 EST 2009


On Feb 9, 9:13 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Tue, Feb 10, 2009 at 2:03 AM, Joel Ross <jo... 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.
>

Changed as suggested above, with further comments:

wordList = "/tmp/Wordlist"
f = open(wordList, 'r')
def readLines():
## There is no point in putting the next four lines
## inside a function if you are going to call the
## function (a) immediately and (b) once only.
## All it does is provide scope for unwanted complications.
   for line in f:
        line = line.rstrip('\n')
        print line + '.com '
## Complications like this next line; why is it returning "line"??
## And why is it indented like that?
## It will cause only the first line to be read.
        return line
## Maybe you you meant it to be here:
    return
## But then it's redundant because a function returns anyway
## when flow of control would fall off the bottom.
readLines()
f.close()

HTH,
John



More information about the Python-list mailing list