For example,
import os
print os.listdir()
list files in directory.
How to get file modification time fo all files in directory ?
For example,
import os
print os.listdir()
list files in directory.
How to get file modification time fo all files in directory ?
When looking for file attributes for all files in a directory, and you are using Python 3.5 or newer, use the
os.scandir()
function to get a directory listing with file attributes combined. This can potentially be more efficient than usingos.listdir()
and then retrieve the file attributes separately:The
DirEntry.stat()
function, when used on Windows, doesn't have to make any additional system calls, the file modification time is already available. The data is cached, so additionalentry.stat()
calls won't make additional system calls.You can also use the
pathlib
module Object Oriented instances to achieve the same:On earlier Python versions, you can use the
os.stat
call for obtaining file properties like the modification time.st_mtime
is a float value on python 2.5 and up, representing seconds since the epoch; use thetime
ordatetime
modules to interpret these for display purposes or similar.Do note that the value's precision depends on the OS you are using:
If all you are doing is get the modification time, then the
os.path.getmtime
method is a handy shortcut; it uses theos.stat
method under the hood.Note however, that the
os.stat
call is relatively expensive (file system access), so if you do this on a lot of files, and you need more than one datapoint per file, you are better off usingos.stat
and reuse the information returned rather than using theos.path
convenience methods whereos.stat
will be called multiple times per file.If you only want the modified time, then
os.path.getmtime(filename)
will get it for you. If you are usinglistdir
with an argument, you'll need to also useos.path.join
: