[Tutor] copy files selectively from source to destination

Alan Gauld alan.gauld at yahoo.co.uk
Mon Dec 5 19:05:08 EST 2016

On 05/12/16 16:20, anatta anatta wrote:

> I however want to copy selective files.
> For example I like to copy only .txt files only 

> How could I do this selective copying?

By applying an if test just before you copy

filetype = '.txt'  # or read it as an input
    if sourcefile extension == filetype
       copy sourcefile to destination

You can extract the extension using the
os.path module functions such as

    Split the extension from a pathname.

    Extension is everything from the last dot to the end, ignoring
    leading dots.  Returns "(root, ext)"; ext may be empty.

>         if not os.path.isfile(newLoc):
>             try:

The if test goes right about here... or you could
even put it higher up before all your tests.

>                 shutil.copy2(oldLoc, newLoc)
>                 print 'File ' + f + ' copied.'
>             except IOError:
>                 print 'file "' + f + '" already exists'

An alternative option is to use glob.glob on the current
folder to get a list of files that match your desired
pattern and copy only those files.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list