Best way to 'touch' a file?

Peter Hansen peter at engcorp.com
Mon Aug 22 18:19:11 EDT 2005


Fredrik Lundh wrote:
> Peter Hansen wrote:
>>from path import path
>>path('myfile').touch()
> 
> import os
> os.utime('myfile', None)
> 
> is a bit shorter, of course.

And, depending on your needs, quite ineffective:

 >>> import os
 >>> os.utime('missing.file', None)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
OSError: [Errno 2] No such file or directory: 'missing.file'

 >>> from path import path
 >>> path('missing.file').touch()
 >>> path('missing.file').exists()
True

I guess it depends on whether "touch" implies creation-when-missing, as 
with the command line version, or just updating the time.

-Peter



More information about the Python-list mailing list