Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy files with specific file extension to a folder in my python (version 2.5) script?

Tags:

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.

like image 933
Amara Avatar asked Nov 17 '08 17:11

Amara


People also ask

How do I copy a file with a specific extension in Python?

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.

How do you list all files in a directory with a certain extension in Python?

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.

How do I copy an entire directory of files into an existing directory using Python?

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.


2 Answers

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()).

like image 193
Federico A. Ramponi Avatar answered Oct 29 '22 21:10

Federico A. Ramponi


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) 
like image 44
bobince Avatar answered Oct 29 '22 19:10

bobince