Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python moving multiple files from one folder to the other based on text characters in file name

I'm quite new to Python. I've been exploring the shutil module and can move things in general. My question revolves around:

Imagine a scenario in which you have hundreds of files in an export folder. While all the files are distinct, 13 of each are for a specific vendor. I would like to create a script that goes through the export folder, evaluates each file name, grabs all the Apple files and puts them in the Apple Folder, Intel files and puts them in the Intel Folder, etc. Any wisdom would be greatly appreciated.

I was trying to have wildcards in the shutil copy, but did not have any luck.

Thanks,

JT

like image 466
user197240 Avatar asked Jul 31 '14 23:07

user197240


3 Answers

Easiest solution I could think of:

import shutil
import os

source = '/path/to/source_folder'
dest1 = '/path/to/apple_folder'
dest2 = '/path/to/intel_folder'

files = os.listdir(source)

for f in files:
    if (f.startswith("Apple") or f.startswith("apple")):
        shutil.move(f, dest1)
    elif (f.startswith("Intel") or f.startswith("intel")):
        shutil.move(f, dest2)

The destination folders do need to exist.

like image 153
Andreas Myriounis Avatar answered Nov 09 '22 09:11

Andreas Myriounis


import glob, shutil

for file in glob.glob('path_to_dir/apple*'):
    shutil.move(file, new_dst)


# a list of file types
vendors =['path_to_dir/apple*', 'path_to_dir/intel*'] 

for file in vendors:
     for f in (glob.glob(file)): 
         if "apple" in f: # if apple in name, move to new apple dir
             shutil.move(f, new_apple_dir)
         else:
             shutil.move(f, new_intel_dir) # else move to intel dir
like image 28
Padraic Cunningham Avatar answered Nov 09 '22 09:11

Padraic Cunningham


Assuming there are specific strings in the file names that identify which vendor the report relates to, you could create a dictionary that maps those identifying-strings to the appropriate vendor. For example:

import shutil
import os

path = '/path/to/location'

vendorMap = {'apple': 'Apple', 
             'intel': 'Intel', 
             'stringID3': 'vendor3'}

files = os.listdir(path)

for f in files:
    for key, value in vendorMap.iteritems():
        if key in f.lower():
            shutil.copy(f, path + '/' + value)
        else:
            print 'Error identifying vendor for', f

This will create a folder in the current directory, named for the appropriate vendor, and copy that vendor's reports there. Note that this example uses the s.lower() method so that it won't matter whether the vendor name is capitalized.

like image 1
user1893148 Avatar answered Nov 09 '22 11:11

user1893148