I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use os.walk
but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.
Copy a File with Python to a Particular PathThe shutil. copyfile() method copies a file to another destination file path, meaning that we need to specify not just the destination directory (folder), but also the filename and extension we want to use.
The method os. listdir() lists all the files present in a directory. We can make use of os. walk() if we want to work with sub-directories as well.
copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying.
import glob, os, shutil files = glob.iglob(os.path.join(source_dir, "*.ext")) for file in files: if os.path.isfile(file): shutil.copy2(file, dest_dir)
Read the documentation of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2() or shutil.copyfile()).
If you're not recursing, you don't need walk().
Federico's answer with glob is fine, assuming you aren't going to have any directories called ‘something.ext’. Otherwise try:
import os, shutil for basename in os.listdir(srcdir): if basename.endswith('.ext'): pathname = os.path.join(srcdir, basename) if os.path.isfile(pathname): shutil.copy2(pathname, dstdir)
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