5

I wish to ignore some directories in my os.walk().

I do:

folders_to_ignore = ['C:\\Users\\me\\AppData\\'];
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
    dir[:] = [d for d in dirs if not is_folder_to_ignore(d)];
    for basename in files:
        if fnmatch.fnmatch(basename, pattern):
            filename = os.path.join(root, basename)
            print("filename=" + filename);

I get:

  File "C:\Users\me\workspaces\pythonWS\FileUtils\findfiles.py", line 29, in find_files
  dir[:] = [d for d in dirs if not is_folder_to_ignore(d)];

TypeError: 'builtin_function_or_method' object does not support item assignment

Any ideas?

Thanks.

dublintech
  • 16,815
  • 29
  • 84
  • 115
  • @mgilson I thought dirs updated this way see: http://stackoverflow.com/questions/5141437/filtering-os-walk-dirs-and-files – dublintech Nov 05 '12 at 19:45
  • @mgilson See the documentation on `os.walk` for what it means to in-place modify the directory list. – dash-tom-bang Nov 05 '12 at 19:45
  • 1
    @dublintech -- you're right. I skimmed through the docs (too) quickly and didn't see that modifying `dirs` in place does in fact make a different. That's pretty cool. Thanks for teaching me something new today! – mgilson Nov 05 '12 at 19:50

1 Answers1

15

You're using dir which is a built-in, probably you mean dirs

change this

dir[:] = [d for d in dirs if not is_folder_to_ignore(d)]

to this

dirs[:] = [d for d in dirs if not is_folder_to_ignore(d)]
millimoose
  • 39,073
  • 9
  • 82
  • 134
Unknown
  • 5,722
  • 5
  • 43
  • 64