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
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).
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.
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.
import glob
import shutil
dest_dir = "C:/test"
for file in glob.glob(r'C:/*.txt'):
print(file)
shutil.copy(file, dest_dir)
Use glob.glob()
to get a list of the matching filenames and then iterate over the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With