简体   繁体   中英

Moving specific file to specific directories

I have lists of files ends with a1, a2.... I want to move a1 to folder1, a2 to folder2 and want to make the folder1 and folder2 directory. I write the code-

import os
import glob, shutil
root_path= ''
folders = ['folder1', 'folder2']

for folder in folders:
    os.mkdir(os.path.join(root_path, folder)

for i in glob.glob ("*a1*","*a2*" ):
   shutil.move (i, 'folders' + i)

I stuck in last portion any help would be much appreciated.

Are you missing the backslashes? Also, you are using the string "folders", if you want to specify the folder you have to change your code.

Try with:

for i in glob.glob ("*a1*"):
   shutil.move (i, folders[0] + "\\" + i)
for i in glob.glob ("*a2*"):
   shutil.move (i, folders[1] + "\\" + i)

PS You can change the code to be more "pythonic" by extracting the folder number from the filename and move the file to the respective folder dynamically, for instance by using regex.

I noticed your code is missing a parrenthese, and also you dont use the folders list at all. I made it working like this. I used a dict to bind the folder names to the text to make it more readable.

import os
import glob

folder_bind = {"a1": "folder1", "a2":"folder2"}

for key, folder_name in folder_bind.items():
    for filename in glob.glob('*'+key+'*'):
        if not os.path.exists(folder_name):
            os.makedirs(folder_name)
        os.rename(filename, folder_name+'/'+filename)

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