Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ignoring directories in os.walk()?

Tags:

python

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.

like image 556
dublintech Avatar asked Nov 05 '12 19:11

dublintech


People also ask

What does OS Walk () do?

OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Does OS walk Change directory?

walk() never changes the current directory, and assumes that its caller doesn't either.

What is the difference between OS Listdir () and OS walk?

listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.

Is OS walk slow?

Python's built-in os. walk() is significantly slower than it needs to be, because – in addition to calling os. listdir() on each directory – it executes the stat() system call or GetFileAttributes() on each file to determine whether the entry is a directory or not.


1 Answers

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)]
like image 111
Unknown Avatar answered Sep 30 '22 14:09

Unknown