python copy files by wildcards

PythonFileCopyGlobShutil

Python Problem Overview


I am learning python (python 3) and I can copy 1 file to a new directory by doing this

import shutil 
shutil.copyfile('C:/test/test.txt', 'C:/lol/test.txt')

What I am now trying to do is to copy all *.txt files from C:/ to C:/test

*.txt is a wildcard to search for all the text files on my hard drive

Python Solutions


Solution 1 - Python

import glob
import shutil
dest_dir = "C:/test"
for file in glob.glob(r'C:/*.txt'):
    print(file)
    shutil.copy(file, dest_dir)

Solution 2 - Python

Use http://docs.python.org/2/library/glob.html#glob.glob">`glob.glob()`</a> to get a list of the matching filenames and then iterate over the list.

Solution 3 - Python

I am using python 2.7 test first to make sure it will work. I used the wildcard * because I add the date to all my text files. filename1_2016_04_18.txt Also some of the text files have different end users attached to the text file. filename2_username.txt

import os, glob

directorypath = 'C:\\Program Files\\Common Files'
os.chdir(directorypath)

files = ['filename1', 'filename2', 'filename3']
print ('A %(files)s'% vars())
for filename in files:
    file1 = filename + "*" + "." + "txt"; print ('1 %(file1)s'% vars())
    file2 = ('%(file1)s') % vars (); print ('2 %(file2)s'% vars())
    file3=glob.glob(file2); print ('3 %(file3)s'% vars())
    for filename4 in file3:
        try:
            if os.path.isfile(filename4):
                    print ('I am deleteing this file %(filename4)s'% vars())
                    os.remove(filename4)
            else:    ## Show an error ##
                    print("Error can not delete text file : %s because file not found" % filename4)
        except OSError, e:  ## if failed, report it back to the user ##
                print ("Error: %s - %s." % (e.filename,e.strerror))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnnyView Question on Stackoverflow
Solution 1 - PythonjseanjView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PythonJamseyView Answer on Stackoverflow