pythondirectoryfile-move

Python - move all files from one folder to another if their file names contain specified words


I have a folder with many files named like homeXXX_roomXXX_high.csv or homeXXX_roomXXX_low.csv, where the XXX part is replaced with a three-digit number.

I want to use some code to move the files into separate folders based on the number next to "home" in the filename. For example, I want to specify that files with names starting home101, home103, home320, home553, etc. should all be moved into folder A whereas those starting with home555, home431, home105 should go to FolderB.

I have this code so far:

import shutil
import os

source = '/path/to/source_folder'
dest1 = '/path/to/FolderA'
dest2 = '/path/to/FolderB'

files = os.listdir(source)

for f in files:
    if (f.startswith("home101") or f.startswith("home103")):
        shutil.move(f, dest1)
    elif (f.startswith("home431") or f.startswith("home555")):
        shutil.move(f, dest2)

However, it's tedious to specify all the if and else cases. I'd like to use some kind of structured data, such as a list, to specify groups of "home" numbers and the corresponding folder paths. How can I do this in Python?


Solution

  • it seems like you can use another for, it would look something like this:

    import shutil
    import os
    
    source = '/path/to/source_folder'
    dest1 = '/path/to/FolderA'
    dest2 = '/path/to/FolderB'
    
    list1 = ["home101", "home103"]
    list2 = ["home431", "home555"]
    
    files = os.listdir(source)
    
    for f in files:
        for home1 in list1:
            if f.startswith(home1):
                shutil.move(f, dest1)
                break
    
        for home2 in list2:
            if f.startswith(home2):
                shutil.move(f, dest2)
                break
    

    You can also create a function:

    def check_and_move(file, list_of_patterns, destination):
        for pattern in list_of_patterns:
            if file.startswith(pattern):
                shutil.move(file, destination)
    

    and the code will get cleaner because you avoid repetition :)

    for f in files:
        check_and_move(f, list1, dest1)
        check_and_move(f, list2, dest2)
        # etc...