how to get files in a directory

Elbert Lev elbertlev at hotmail.com
Wed Sep 29 21:38:40 CEST 2004


Anand K Rayudu <ary at esi-group.com> wrote in message news:<mailman.4078.1096469771.5135.python-list at python.org>...
> Hi all,
> 
> I am trying to find a way to get the files recursively in a given 
> directory,
> 
> The following code is failing, can some one please suggest what could be 
> problem here
> 
> 
> from os import walk,join
> 
> for root,dir,files in os.walk("E:\myDir1\MyDir2"):
>    for i in dir:
>        for j in files:
>            fille = root+i+j
>             print file
> 
> Surprisingly if i give os.walk("E:\myDir1") the above code works, but 
> not if i have 2 levels of directories.
> 
> Thanks & Best Regards,
> Anand


All is wrong!
0. Wrong import
1. not "E:\myDir1\MyDir2", but "E:\\myDir1\\MyDir2"
2. dir and files are in the SAME directory. In other words if the
structure is:
myDir1
    MyDir2
       somefile.py
the first itteration will give an EMPTY dir= [] and files =
['somefile.py']


Here is an example from the manual:

This example displays the number of bytes taken by non-directory files
in each directory under the starting directory, except that it doesn't
look under any CVS subdirectory

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum([getsize(join(root, name)) for name in files]),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

so if you want just print full path of the files in E:\myDir1\MyDir2

for root,dir,files in os.walk("E:\myDir1\MyDir2"):
    for j in files:
        fille = os.path.join(root,j)
        print fille

Do not touch dir. It is supposed to be used to restrict the search.
If you do not modify dir it walk will progress into root's
subdirectories.



More information about the Python-list mailing list