Home > database >  Moving only images in a directory to a new directory
Moving only images in a directory to a new directory

Time:02-06

I have a directory containing N images, but each image is itself contained in a subdirectory, which is otherwise empty. It looks like this:

- Images
 - Image1
   - image1.jpg
 - Image2
   - image2.jpg
 - Image3
   - image3.jpg
 - Image4
...etc

I would like to move it to a new directory that will contain only the images, like so:

- New Directory
 - image1.jpg
 - image2.jpg
 - image3.jpg
...etc

Any help is greatly appreciated.

CodePudding user response:

    import os, shutil, pathlib, fnmatch
    
    def move_dir(src: str, dst: str, pattern: str = '*'):
        if not os.path.isdir(dst):
            pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
        for f in fnmatch.filter(os.listdir(src), pattern):
            shutil.move(os.path.join(src, f), os.path.join(dst, f))
#easy to use
    move_dir('Images/Image1','New Directory','jpg')

Source: How to move a file in Python?

CodePudding user response:

This simple solution ended up working for me:

import os

rootdir = './Images'

for subdir, dirs, files in os.walk(rootdir):
  for file in files:
    os.rename((os.path.join(subdir, file)),'./NewDirectory/' str(file))
  •  Tags:  
  • Related