Home > front end >  Create folder by files year
Create folder by files year

Time:07-24

I have a lot of pictures in a paste following a pattern for the file name. For instance:

IMG-20211127-WA0027.jpg
IMG-20211127-WA0028.jpg
IMG-20211127-WA0029.jpg

I'm trying to find a way to create a folder for each year and send the pictures for the respective folder, given that the file name already has its year. How can I create folders for each year, move the files to the right folder?

I tried to adapt a code from a tutorial, but I'm not getting what I need. Please see my code below :

from distutils import extension
import os 
import shutil

path = "D:\WhatsApp Images"
files = os.listdir(path)
year = os.path.getmtime(path) 

for file in files:
    filename, extension = os.path.splitext(file)
    extension = extension[1:]

    if os.path.exists(path '/' extension):
        shutil.move(path '/' file, path '/' extension '/' file)
    
    else:
        os.makedirs(path '/' extension)
        shutil.move(path '/' file,path '/' extension '/' file)

CodePudding user response:

I like @alexpdev 's answer, but you can do this all within pathlib alone:

from pathlib import Path

path_to_your_images = "D:\\WhatsApp Images"
img_types = [".jpg", ".jpeg"] # I'm assuming that all your images are jpegs. Extend this list if not.

for f in Path(path_to_your_images).iterdir():
    if not f.suffix.lower() in img_types:
        # only deal with image files
        continue
    year = f.stem.split("-")[1][:4]
    yearpath = Path(path_to_your_images) / year # create intended path
    yearpath.mkdir(exist_ok = True) # make sure the dir exists; create it if it doesn't
    f.rename(yearpath / f.name) # move the file to the new location

CodePudding user response:

You can try something like this: See the inline comments for an explanation.

from pathlib import Path
import shutil
import os

path = Path("D:\\WhatsApp Images")  # path to images

for item in path.iterdir(): # iterate through images
    if not item.suffix.lower() == ".jpg":   # ensure each file is a jpeg
        continue
    parts = item.name.split("-")
    if len(parts) > 1 and len(parts[1]) > 5:
        year = parts[1][:4]  # extract year from filename
    else:
        continue
    if not os.path.exists(path / year):    # check if directory already exists
        os.mkdir(path / year)              # if not create the directory
    shutil.move(item, path / year / item.name)   # copy the file to directory.
  • Related