Question on time module

Peter Hansen peter at engcorp.com
Sun Jun 2 10:36:18 EDT 2002


Gold Fish wrote:
> 
> Can anyone tell me how to sort the file in the directory according to their
> modification time. Then if i want to look up a find say python.txt Mar 04
> 2002 in the directory can i use glob.glob to do it. I using
> time.localtime(time.time()) to get the current time in, how can i display
> only the file in the directory 5 days agos from the current time. Please
> help me to solve this problem. I tried to use os.stat to seperate the file
> time but it couldn't work.

C:\> rem Create file that appears five days old
C:\> touch -d 05-28-2002 target.txt

>>> import os,time,stat

>>> # Retrieve all files in current directory
>>> files = [x for x in os.listdir('.') if os.path.isfile(x)]

>>> # make each entry into tuple with modification time first
>>> files = [(time.localtime(os.stat(x)[stat.ST_MTIME]), x) for x in files]
>>> files.sort()
>>> print files
[((1999, 4, 23, 22, 22, 0, 4, 113, 1), 'COMMAND.COM'), ((2002, 1, 4, 20, 35, 32,
4, 4, 0), 'CONFIG.DOS'), ((2002, 1, 4, 20, 42, 14, 4, 4, 0), 'AUTOEXEC.DOS'), ((
2002, 1, 5, 0, 52, 58, 5, 5, 0), 'MSDOS.SYS'), ((2002, 1, 5, 1, 57, 10, 5, 5, 0)
, 'SETUPLOG.TXT'), ((2002, 1, 23, 21, 12, 24, 2, 23, 0), 'AUTOEXEC.BAT'), ((2002
, 1, 23, 21, 12, 24, 2, 23, 0), 'CONFIG.SYS'), ((2002, 5, 28, 10, 31, 46, 1, 148
, 1), 'TARGET.TXT'), ((2002, 6, 2, 1, 53, 42, 6, 153, 1), 'SCANDISK.LOG')]

>>> # create tuple for current date (only year,month,day needed)
>>> oldTime = time.localtime(time.time() - 5*24*60*60)[:3]
>>> # make list of files with matching dates
>>> fiveDayOldFiles = [x[1] for x in files if x[0][:3] == oldTime]
>>> print fiveDayOldFiles
['TARGET.TXT']

Note: I wouldn't use exactly the above code for this, since it's not highly
readable, but it should give you the basics.

-Peter



More information about the Python-list mailing list