Working with directory

Kragen Sitaker kragen at pobox.com
Tue May 28 18:13:08 EDT 2002


"Occean" <tritran2001 at iprimus.com.au> writes:
> I have to write the function that read in to the existing directory and
> display some files according to their date for example, in my PyExample
> directory i got 
> 
> practice1.py    Thu Mar 16 11:54:21 2002
> practice2.py    Thu Mar 17 10:25:22 2002
> ..
> practice7.py     Friday Apr 28 1:20:22 2002
> 
> i want to  just get 2 files from that directory which are from Mar or
> specific time only. How can i do that, and which built in function allow
> me to view all the file in directory with time. By looking the reference
> os.time.stat but i can't work out the solution for this problem.

os.listdir(dirname) lists the directory.

os.stat(pathname)[stat.ST_MTIME] is the modification time of the file,
as a number of seconds since 1969 GMT.

time.localtime(nsecs) converts a number of seconds since 1969 GMT into
a tuple giving year, month, day, etc.

os.path.join(dirname, filename) will be useful in combining the stuff
you get back from os.listdir into full pathnames you can pass to
os.stat.

So you want a loop something like this:
import os, time, stat
dirname = '.'
for filename in os.listdir(dirname):
    date = time.localtime(os.stat(os.path.join(dirname, filename))[stat.ST_MTIME])
    if date[1] == 3:  # element 1 is month
        print filename, time.asctime(date)

HTH.




More information about the Python-list mailing list