Dynamic text color

John Posner jjposner at optimum.net
Tue Jan 5 12:53:01 EST 2010


On Tue, 05 Jan 2010 10:31:09 -0500, Dave McCormick <mackrackit at gmail.com>  
wrote:

> ... But this is what I have so far.
> ##############
> file = 'red.txt'
> file = open("red.txt","r")
> rList = file.readlines()
> file.close()
> redList = str(rList).split()

Dave, you're doing exactly the right thing: gradually expanding your  
program, to provide more functionality and to learn more about the  
available programming tools. It's also very good that you take care to  
close() the file after processing it. Now for the bad news ...

1. Don't use "file" as a variable name -- it's a built-in object type.  
(Some people don't like the fact that Python allows you to redefine such  
"reserved words".)

2. It's probably not the best idea to use a single variable (you use  
"file") to do double-duty: to hold the name of a file, and to hold the  
open-file object returned by the open() function. It's perfectly legal,  
but it hides information that might be useful when you're debugging a  
program. This is better:

   fname = 'red.txt'
   inpf = open(fname, "r")

3. It might be better to use read() rather than readlines() to process the  
"red.txt" file. It depends on what that file is supposed to contain. For  
example, if you expect "red.txt" to contain exactly one line, which has  
one or more words, you can process the open-file object like this:

   file_contents = inpf.read()
   redList = file_contents.split()

    ... or ...

   redList = inpf.read().split()

It's certainly a mistake to use the expression "str(rList).split()". Using  
str() to convert the list "rList" into a string creates a mess that  
includes square-bracket characters. Did this actually work for you?

Best,
John




More information about the Python-list mailing list