Home > Back-end >  python elegant way to create folders and move files
python elegant way to create folders and move files

Time:09-11

Currently, I have more than 30 .xlsx files in my source folder.

All these 30 files are from different regions in APAC which has keywords such as IND, KOR, ASN etc.

My objective is to do the below

a) create separate folders for each region (ASN, KOR and IND)

b) Copy .xlsx files with region keywords to appropriate folders.

So, I tried the below

if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\IND'):
    os.mkdir('C:\\Users\\test\\Downloads\\output_data\\IND')
if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\ASN'):
    os.mkdir('C:\\Users\\test\\Downloads\\output_data\\ASN')
if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\KOR'):
    os.mkdir('C:\\Users\\test\\Downloads\\output_data\\KOR')
if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\ASN_ANZ_KR'):
    os.mkdir('C:\\Users\\test\\Downloads\\output_data\\ASN_ANZ_KR')
    
source = 'C:\\Users\\test\\Downloads\\output_data'
IND = 'C:\\Users\\test\\Downloads\\output_data\\IND'
ASN = 'C:\\Users\\test\\Downloads\\output_data\\ASN'
KOR = 'C:\\Users\\test\\Downloads\\output_data\\KOR'
ASN_ANZ_KR = 'C:\\Users\\test\\Downloads\\output_data\\ASN_ANZ_KR'

files = os.listdir(source)

for f in files:
    if ("IND.xlsx" in f):
        shutil.move(f, IND)
    elif ("ASN.xlsx" in f) or ("ANZ.xlsx" in f):
        shutil.move(f, ASN)
    elif ("KOR.xlsx" in f):
        shutil.move(f, KOR)
    elif ("KR.xlsx" in f):
        shutil.move(f, ASN_ANZ_KR)
    else:
        a=0   # do nothing so, assign a dummy value to a variable

Though the above code works fine, is there any other better way to write this?

You can see i write multiple if conditions (multiple times) for creating folders and then to copy files based on wildcard.

Is there any better elegant and efficient approach available to do the above task?

CodePudding user response:

I would do something like this, here is the annotated code:

from pathlib import Path

# mapping of filename match pattern to destination directory name
dct = {'IND': 'IND', 'ASN': 'ASN', 'KOR': 'KOR', 'KR': 'ASN_ANZ_KR'}

src = Path(source)
for key, val in dct.items():
    for file in src.glob(f'*{key}.xlsx'):
        # ensure destination directory exists
        dest = src / val
        dest.mkdir(exist_ok=True)

        # Move the file from source to destination
        file.rename(dest / file.name)
  • Related