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.
views:
1645answers:
5
+4
Q:
How do I copy files with specific file extension to a folder in my python (version 2.5) script?
+6
A:
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()).
Federico Ramponi
2008-11-17 17:06:37
@J.F. Sebastian: Thank you for the improvements!
Federico Ramponi
2008-11-18 21:11:08
+1
A:
This will walk a tree with sub-directories. You can do an os.path.isfile check to make it a little safer.
for root, dirs, files in os.walk(srcDir):
for file in files:
if file[-4:].lower() == '.jpg':
shutil.copy(os.path.join(root, file), os.path.join(dest, file))
Deon
2008-11-17 19:39:10
it is an error to use `.lower()` on case-sensitive systems (MS Windows is dominant but it is not a whole world). `os.path.normcase(file)` is preferred instead.
J.F. Sebastian
2008-11-18 22:47:16
+4
A:
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)
bobince
2008-11-17 19:39:49
`basename = os.path.normcase(basename)` before `basename.endswith` could be useful (on Windows).
J.F. Sebastian
2008-11-18 22:53:59
+2
A:
Here is a non-recursive version with os.walk
:
import fnmatch, os, shutil
def copyfiles(srcdir, dstdir, filepattern):
def failed(exc):
raise exc
for dirpath, dirs, files in os.walk(srcdir, topdown=True, onerror=failed):
for file in fnmatch.filter(files, filepattern):
shutil.copy2(os.path.join(dirpath, file), dstdir)
break # no recursion
Example:
copyfiles(".", "test", "*.ext")
J.F. Sebastian
2008-11-18 18:32:59