Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python copy files by wildcards

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

like image 952
Johnny Avatar asked Aug 22 '13 04:08

Johnny


People also ask

Which wildcard is used for copying all files?

As an alternative to entering a new name for each file, you can use a simple wildcard system to rename all copied or moved files at once. This is not a full pattern matching (or regular expressions) system; instead, the only wildcard character that's recognised is * (the asterisk).

How do you copy multiple files in Python?

Sometimes we need to copy an entire folder, including all files and subfolders contained in it. Use the copytree() method of a shutil module to copy the directory recursively. This method recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory.

How do I copy all files in a directory in Python?

The shutil. copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another. The destination should not be an existing directory.


2 Answers

import glob
import shutil
dest_dir = "C:/test"
for file in glob.glob(r'C:/*.txt'):
    print(file)
    shutil.copy(file, dest_dir)
like image 186
jseanj Avatar answered Oct 17 '22 02:10

jseanj


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

like image 29
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 02:10

Ignacio Vazquez-Abrams