Working with directory

inkedmn at earthlink.net inkedmn at earthlink.net
Fri Jun 7 22:52:28 EDT 2002


On 28 May 2002 18:13:08 -0400, Kragen Sitaker <kragen at pobox.com>
wrote:

>"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.
>


hello...

formatting the date/time is pretty easy if you use the asctime method
in the time module.

like this:
>>> import time
>>> x = time.asctime()
>>> print x
Fri Jun 07 19:46:18 2002

one of my personal favorites :)

hope this helps

ink





More information about the Python-list mailing list