简体   繁体   中英

Python: Move files to folder based on Part of File name

Folder contains files

  1. filenameone_partone_1
  2. filenameone_partone_2
  3. filenameone_partone_3
  4. filenameone_parttwo_1
  5. filenameone_parttwo_2
  6. filenametwo_1
  7. filenametwo_2

Now i want to move (1,2,3)(4,5)(6,7) to each folder. Based on file name folder has to be created and respective files to be moved. The following code works but file name it has in character range x:y but that will not works above file name examples.SO need some modification in file name pass.Thanks.

     import os, shutil
        os.chdir("<abs path to desktop>")
        for f in os.listdir("folder"):
            folderName = f[0:10]
            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)

Assumption being file will always end with "_number"

     import os, shutil
        os.chdir("<abs path to desktop>")
        for f in os.listdir("folder"):
            folderName = f[0:-2]
            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)




The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM