So you are running programs from python now. Perhaps you want to check that a file is readable and executable before trusting it to run? The os module comes to the rescue once again!
import os filename = 'bin/someprogram' if not os.path.exists(filename): print filename, 'does not exist!' raise SystemExit, 2 if not os.access(filename, os.R_OK): print filename, 'is not readable!' raise SystemExit, 3 if not os.access(filename, os.X_OK): print filename, 'is not executable!' raise SystemExit, 4
We would like to know that the file exists. This is determined with os.path.exists. Is the file readable and executable? We can find out with os.access and a couple of constants from the os module, os.R_OK and os.X_OK. We could also test if a file is writeable with os.access. We just use the os.W_OK constant. Simple, yes?
Would you like to know the times of creation, modification, and access? What about file size?
import datetime import os filename = 'somedir/somefile' ctime = datetime.datetime.fromtimestamp(os.path.getctime(filename)) mtime = datetime.datetime.fromtimestamp(os.path.getmtime(filename)) atime = datetime.datetime.fromtimestamp(os.path.getatime(filename)) sizeinbytes = os.path.getsize(filename)
It is pretty straight forward. You might be wondering about why I am using datetime.datetime.fromtimestamp here. The os.path.getXtime functions all spit out POSIX timestamps. In python, it is more useful to have these be python datetimes. The datetime.datetime.fromtimestamp function produces a datetime object from a given timestamp.
