I need to write a Python script to sort pictures, how would I do this?

What I'm looking for is a script that can go through a huge list of pictures and sort them into folders.

So I take pictures of dogs at shows, so lets say I take several pictures of dog1, this dogs picture are automatically named in serial number format (Dog1-1, Dog1-2, Dog1-3, etc). Dog2 would follow the same format.

I'd like a script that can take Dog1-1-10 and move them into a folder named Dog 1. Dog2-1-10 into a folder named Dog 2, etc.

How can this be done in Python?


So basically, what you want to do is:

  • Find every file in a given folder
  • Take the first part of each filename and use that as the folder name
  • If the folder doesn't exist, create it
  • Move the file into that folder
  • Repeat
  • Well, nifty! Figuring out what we want to do is half the battle -- now, it's mostly a matter of googling and turning this into code.

    First, we need the folder to check in:

    folder_path = "myfolder"
    

    Now, we want to find every file inside that folder. A quick googling session turns up this:

    import os
    import os.path
    
    images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
    

    As an aside, I'm going to be using os.path.join a fair bit, so you may want to briefly read up on what it does. The guide you linked to in the comments covers it fairly well.

    Now, we want the first part of each name. I'm going to assume that we'll treat everything up the first dash as the folder name, and ignore the rest. One way to do that is to use string.split , which splits a string by the given character into a list of strings, and grab the first element:

    for image in images:
        folder_name = image.split('-')[0]
    

    Now, if that folder doesn't already exist, we want to create it. Again, google is our friend:

    new_path = os.path.join(folder_path, folder_name)
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    

    And finally, we move the original image:

    import shutil
    
    old_image_path = os.path.join(folder_path, image)
    new_image_path = os.path.join(new_path, image)
    shutil.move(old_image_path, new_image_path)
    

    Putting it all together:

    import os
    import os.path
    import shutil
    
    folder_path = "test"
    
    images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
    
    for image in images:
        folder_name = image.split('-')[0]
    
        new_path = os.path.join(folder_path, folder_name)
        if not os.path.exists(new_path):
            os.makedirs(new_path)
    
        old_image_path = os.path.join(folder_path, image)
        new_image_path = os.path.join(new_path, image)
        shutil.move(old_image_path, new_image_path)
    
    链接地址: http://www.djcxy.com/p/9278.html

    上一篇: 正确处理logging.config.fileConfig抛出的IOError?

    下一篇: 我需要编写一个Python脚本来排序图片,我该怎么做?