Python: Moving files to folder based on filenames

后端 未结 1 880
夕颜
夕颜 2020-12-11 07:25

I have a folder with 10 images that I wish to move into a new folder based on it\'s current filenames. I\'ve successfully been able to move every images in the folder into a

相关标签:
1条回答
  • 2020-12-11 08:04

    You can just try to use os.path.exists() to check if the folder exists, if it exists copy the jpg into it. By the way it's better if you use copy, because when you use move you are basically mixing everything up if you do something wrong.

    import os, shutil
    
    os.chdir("<abs path to desktop>")
    
    for f in os.listdir("folder"):
        folderName = f[-6:-4]
    
        if not os.path.exists(folderName):
            os.mkdir(folderName)
            shutil.copy(os.path.join('folder', f), folderName)
        else:
            shutil.copy(os.path.join('folder', f), folderName)
    

    0 讨论(0)
提交回复
热议问题