HELP: Python equivalent of UNIX command "touch"

P

pekka niiranen

Does anybody know Python recipe for changing the date
of the directory or files in W2K to current date and time?
In UNIX shell command "touch" does it.

-pekka-
 
R

Roy Smith

pekka niiranen said:
Does anybody know Python recipe for changing the date
of the directory or files in W2K to current date and time?
In UNIX shell command "touch" does it.

You want os.utime()
 
R

Roy Smith

Nope, it does not work for directories in Windows

Well, there's always the old fashioned way (which early versions of
touch used). Read the first byte of the file, rewind, write the byte
back out, seek to the end (to preserve the file length), and close the
file. I'm not sure what to do for directories (I guess you could
create and delete a temp file).

Of course, if you told me that doesn't work on Windows either, I
wouldn't be too surprised. :)
 
W

Wolfgang Strobl

pekka niiranen said:
Does anybody know Python recipe for changing the date
of the directory or files in W2K to current date and time?
In UNIX shell command "touch" does it.

See below. The key is using the FILE_FLAG_BACKUP_SEMANTICS flag.

#----------------------------------------------------------------------------------
# dirtest.py
from win32file import *
from pywintypes import Time
import time
x=CreateFile(r"d:\scratch\testdir",GENERIC_READ+GENERIC_WRITE,
FILE_SHARE_WRITE,None,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,0)
i,c,a,w= GetFileTime(x)
print "create",c,"access",a,"write",w
SetFileTime(x,Time(int(c)-24*3600),Time(int(c)-12*3600),Time(int(c)
-3*3600))
#----------------------------------------------------------------------------------

C:\e\littlepython>dirtest.py
create 01/21/05 04:27:04 access 01/21/05 16:27:04 write 01/22/05
01:27:04

C:\e\littlepython>dirtest.py
create 01/20/05 03:27:04 access 01/20/05 15:27:04 write 01/21/05
00:27:04

C:\e\littlepython>dir d:\scratch\testdir
....
Verzeichnis von d:\scratch\testdir

20.01.2005 00:27 <DIR> .
20.01.2005 00:27 <DIR> ..
0 Datei(en) 0 Bytes
2 Verzeichnis(se), 806.768.640 Bytes frei
 
T

Tim G

Since no-one's suggested this yet, I highly recommend
UnxUtils: http://unxutils.sourceforge.net/ which includes
a touch.exe. Obviously, this doesn't answer your call for
a Python version, but if you're happy with touch under
Unix, maybe this will work for you.

TJG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top