I'm an idiot

Carel Fellinger carel.fellinger at iae.nl
Sat Jun 29 05:15:56 CEST 2002


On Sat, Jun 29, 2002 at 01:00:22AM +0000, David wrote:
> OK, I am the first to admit it.  I am an idiot.  I have RTFM on this over 

Hm, that makes you the first idiot to admit he's an idiot, not likely so.

...
> And just to explain my stupidity, my reference langauge is BASIC.  I 

Hm, nothing wrong with having BASIC as your reference language, it just
indicates that you haven't had the time to familiarize yourself with
Python.  Don't worry, in a few days all will be swell.


> f=open('c:\\temp\\temp.txt', 'r')

Windows allows / in dir path, less error prone, and "r" is the default
mode and hence often left out.

> g=open('c:\\temp\\temp1.txt', 'w')
> while 1:
>     try:
>         s=f.readline

here you merely create an extra name for the file readline function.
The ( and ) are really needed to instruct the interpreter to perform
the function instead of creating a new name for it.

>         g.write(s.split())

the split method removes all spaces/newlines/tabs from a string, braeking
the string in those places and returning a list of al the leftovers.

  "a      bc d".split()  ==  ["a", "bc", "d"]

>     except IOError:
>         break

In python the file read(line) method(s) don't bark at the end of file,
they simply return an empty string. So you won't get an EndOfFile
Exception.  The easiest thing is to test here for the empty string.

> 
> g.close
> f.close

again, without the ()'s nothing happens here.

Fixing the above and replacing the non-working try-except you get:

   f = open('c:/temp/temp.txt')
   g = open('c:/temp/temp1.txt', 'w')
   while 1:
       line = f.readline()
       line = line.strip()
       if not line:   # line is empty
            break
       g.write(line)
   g.close()
   f.close()


But we can do better then this by replacing the while loop with a for loop:

   f = open('c:/temp/temp.txt')
   g = open('c:/temp/temp1.txt', 'w')
   for line in f.readlines():
       g.write(line.strip())
   g.close()
   f.close()


And in Python2.* the above for line can be further simplified as:

   f = open('c:/temp/temp.txt')
   g = open('c:/temp/temp1.txt', 'w')
   for line in f:
       g.write(line.strip())
   g.close()
   f.close()


Many people would rely on Python's automatic file closing behaviour
and write it like this:

   g = open('c:/temp/temp1.txt', 'w')
   for line in open('c:/temp/temp.txt'):
       g.write(line.strip())


-- 
groetjes, carel






More information about the Python-list mailing list