[Tutor] Is there a file creator?

Christian Tismer tismer@tismer.com
Mon, 07 Oct 2002 13:45:32 -0700


Gus Tabares wrote:
> SA,
> 
> 	I think when you open a file in write mode, if the file doesn't
> already exists, it will be created, hence, it will start empty. Hope this
> helps...
> 
> 
> Gus
> 
> On Fri, 6 Sep 2002, S A wrote:
> 
> 
>>Is there a function or module that creates an empty file like the unix command "touch" does?

Well, a real equivalent of "touch" would have to set the
time stamp of an existing file to now, without changing
the file. Opening in write mode would clear it.
For that purpose, os.utime seems to be appropriate, since
it appears to work, whether the file is opened or not.

something like (not tested):

import os, time

def touch(path):
   if os.path.exists(path):
     t = time.time()
     os.utime(path, (t, t) )
   else:
     file(path, 'w').close()

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer@tismer.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  pager +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/