[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

splitext(p)
    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.
(END)


>         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.


hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list