[Tutor] Re: Tutor digest, Vol 1 #2302 - 11 msgs

Magnus Lycka magnus@thinkware.se
Wed Mar 5 17:13:01 2003


Anton Muhin wrote:
>inText = file(r"c:\file.txt").read()
>inText.replace("old", "new")
>
>outFile = file(r"output.txt", 'w')
>outFile.write(inText)
>outFile.close()
>
>Several notes:
>1. You'd better avoid names like 'file' for variables---it's actually
>a built-in function.

Not function, type. In Python 2.2 and up, types are like classes,
and can be used to instanciate objects just like any class:

 >>> int("23")
23
 >>> float(6)
6.0
 >>> str('Hello')
'Hello'
 >>> file('c:/autoexec.bat')
<open file 'c:/autoexec.bat', mode 'r' at 0x025AFBC0>

>2. You mustn't import string module (at least for your example)

I think Anton meant "you don't have to import the string module".
Anton: English is a bit strange on negating must. Mustn't means
"you are not allowed to". I.e. from a binding point of view, it's
"must (not do)". You'd expect it to be "(must not) do", right. It
seems russian is like Swedish here...

>3. Don't forget to close files (althoug I think Python might close it
>for you, but still).

Which Anton didn't do above after reading the file. :)

In C-Python, this will not matter in the current implementation,
since the file will be closed directly due to the reference
counting garbage collection. In Jython, Java might well decide
not to garbage collect yet, and then you try to open a file for
writing which is already open for reading. Can you do that?

>4. You may use r" to avoid \\ ugliness

Better to use / for path separators as God intended, unless
you run a Mac. For platform indenpence, use os.path.join().

Drew Perttula wrote:
>Almost-- Python strings are immutable, meaning that once the read()
>method created the string it returned, that string object will never
>change. So, even though the string object does indeed have a replace()
>method, that method can't alter the string in place: instead, it returns
>a new string with the changes.
>
>So here's the fix:
>
>infile = open('c:/file.txt')
>s = infile.read()
>s=s.replace('old', 'new')

Oops, we all forgot that, didn't we? It's easy to determine
where a problem lies, and copy someone elses code without
really checking it...

>I changed 'file' so it's not the name of a builtin type, like someone
>else suggested. And, I replaced s with the new string returned by the
>replace() method. The rest of the program that writes s to a file doesn't
>have to change.

If we use python 2.2 or newer, where file is a builtin type,
we might as well use that.

infile = file('c:/file.txt')

On the other hand, using open() it will run with older pythons as well...


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se