78

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

Ivo
  • 3,481
  • 1
  • 25
  • 29
Johnny
  • 789
  • 1
  • 5
  • 3

3 Answers3

123
import glob
import shutil
dest_dir = "C:/test"
for file in glob.glob(r'C:/*.txt'):
    print(file)
    shutil.copy(file, dest_dir)
scottclowe
  • 2,015
  • 19
  • 20
jseanj
  • 1,509
  • 1
  • 9
  • 9
  • 1
    What is the r in glob.glob(r ? – Ridhuvarshan May 02 '18 at 13:44
  • I ask the same... For example, I dindn't found anything regarding this `r` on the official doc (https://docs.pytahon.org/3.5/library/glob.html). Also, I tried to use the solution without the argument and it seems and nothing has changed. Some `glob` master: please, clarify this doubt. Anyway: great answer :). – ivanleoncz May 02 '18 at 16:27
  • 18
    I found out the answer @ivanleoncz . The r is used before a string in python to override escape sequences (ie \n will be considered as \n and not as a new line). In the answer, using r makes no difference because no escape sequences are there, but if the file separator was \ instead of /, then the impact would be noticed. To put it in other words, r has got nothing to do with glob. It is a prefix that can be used before strings in python – Ridhuvarshan May 03 '18 at 10:15
  • 2
    It's called a raw string in python :) https://docs.python.org/2.0/ref/strings.html – timtody Sep 23 '19 at 07:00
  • Note: glob doesn't seem to resolve `~` for the home directory on linux. – zanbri Mar 03 '23 at 21:44
13

Use glob.glob() to get a list of the matching filenames and then iterate over the list.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
-4

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))
Jamsey
  • 1
  • By checking whether a file with a name that `glob.glob` just returned actually exists you are making it... thread-safe? (You are not.) – bers Apr 09 '18 at 07:40
  • What is the difference between variables `file2` and `file1`? – bers Apr 09 '18 at 07:41