Welcome, guest | Sign In | My Account | Store | Cart

I wanted to do a conditional copy of a directory tree. Noticed a ignore parameter introduced in Python 2.6. Thats very handy. This snippet gives the example of its usage.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import os
import shutil

SOURCE_DIR = os.getcwd()
TARGET_DIR = 'web'
IGNORE_PATTERNS = ('*.pyc','CVS','^.git','tmp','.svn')

if os.path.exists(TARGET_DIR):
    shutil.rmtree(TARGET_DIR)

shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns(IGNORE_PATTERNS))

This would be helpful when you want to create a source tarball out of your cvs/svn/git tree. Also if are about to create a html website directory from your source tree.

1 comment

Daniel Tavares 11 years, 7 months ago  # | flag

There's a bug on this example. You're missing the '*' when calling shutil.ignore_patterns, also, '^.git' doesn't prevent the git directory from being copied.

These are the changes I had to make:

@line 6:
-IGNORE_PATTERNS = ('.pyc','CVS','^.git','tmp','.svn')
+IGNORE_PATTERNS = ('
.pyc','CVS','.git','tmp','.svn')

@line 11:
-shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns(IGNORE_PATTERNS)) +shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns(*IGNORE_PATTERNS))