Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last modified date of a directory (including subdirectories) using Python?

Tags:

python

I am trying to get the last modification date and time of a directory. while doing that I want to include the last modified date of the sub directories as well.

I could find some topics related to this question.(How to get file creation & modification date/times in Python?) but all of those just gives the last modified time of the root directory without considering the sub directories.

import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime(file))
print "created: %s" % time.ctime(os.path.getctime(file))

These lines of code just gives the last modified time of the root directory without considering the sub directories. Please help me on this.

like image 672
user4k Avatar asked Apr 16 '15 20:04

user4k


People also ask

Which function is used to get the last modification time?

Using getlastmod() Function: The getlastmod() function is used to get the last modification time of the current page.

How do I find the last modified date of a file?

The last modifying date of the file can get through Java using the File class of Java i.e File. LastModified() method. The File class is Java's representation of a file or directory pathname.


1 Answers

This should do what you ask:

import os
import time

print time.ctime(max(os.stat(root).st_mtime for root,_,_ in os.walk('/tmp/x')))

But I see you use os.path.getmtime(). So you are probably looking for this:

print time.ctime(max(os.path.getmtime(root) for root,_,_ in os.walk('/tmp/x')))
like image 155
Robᵩ Avatar answered Sep 21 '22 20:09

Robᵩ