os.walk()

Chris Rebert clp2 at rebertia.com
Thu Aug 6 17:08:15 EDT 2009


> On Tue, Aug 4, 2009 at 10:48 PM, Chris Rebert <clp2 at rebertia.com> wrote:
>> On Tue, Aug 4, 2009 at 7:06 PM, Michael Savarese<geomajor56 at gmail.com> wrote:
>> > Greetings
>> > Python newbie here, and thanks to all who have helped me previously.
>> > Is there a way of grabbing file attributes while traversing with os.walk()?
>> > It would be advantageous to have date modified and file size along with the
>> > file name.
>> > If anyone can point me in the right direction, I'd appreciate it.
>>
>> Feed the path to os.stat(), and then use the `stat` module on the result:
>> http://docs.python.org/library/os.html#os.stat
>> http://docs.python.org/library/stat.html#module-stat

2009/8/5 Michael Savarese <geomajor56 at gmail.com>:
> Chris, thanks for the info.
> I'm a bit stuck here.
>
> am i close?

Yes, you just need to plug some more bricks together (as it were).

> import os, sys
> import os.path
>
> for root, dirs, files in os.walk('c:/Temp'):
>     for name in files:
>         statinfo=os.stat(name)
#see http://docs.python.org/library/os.path.html#os.path.join
        filepath = os.path.join(root, name)
        statinfo = os.stat(filepath)
>
>           print root,dirs,name,statinfo.st_size ; it gets stuck here, i guess it needs the full path.
>                                                                  is this where i use the join function to bring root, dirs, and filename together?
>                                                                  I kinda suck at that too, can you point me in the right direction?
>
> also:
>>>> statinfo.st_mtime
> 1247778166.6563497  can i have a hint on how to convert this?

That is the time represented in seconds since the (UNIX) epoch.
Use the functions in the `time` module to convert it to something more
palatable:
http://docs.python.org/library/time.html

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list