0

How to move all only one type of file to another directory? For example, i want to move only all .jpg only file to another folder in Python. I know batch is easier to do it, but i prefer in Python. Anyone can help?

4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by zachabesh
0

I would use os.listdir, and shutil.move (or copy). Here's a useful function to sort by extension:

def filterbyext(filelist,ext):
    """Returns all files of type ext in filelist"""
    returnfiles = []
    for item in filelist:
        x = item.split(".")
        try:
            #Take all files of THIS type
            if str(x[1]) == ext:
                returnfiles.append(item)
        except IndexError:
            pass
    return returnfiles

So this is what it would look like:

for jpg in filterbyext(os.listdir(os.getcwd()),'jpg'):
     shutil.move(jpg,newdest)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.