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

Question:

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?

Asked By: Jay

||

Answers:

You can make an array for folderA that contains the "home+number"

FolderAGroup = ['home101', 'home103', 'homeXXX', 'homeXXX']

And if they get split like you say with a "_" use this code to filter them
Won’t work if they are not split like that.

files = os.listdir(source)

for f in files:
  parts = f.split('_')
  # Get the first part of the filename before the _
  home_number = parts[0]
  # Check if the home number is in the FolderA group array
  if home_number in FolderAGroup:
    shutil.move(f, dest1)
  else:
    shutil.move(f, dest2)

You can expand with more elif statements if you would want more folders.

Answered By: Seppe Willems

If the names homexxx are incremental, you could try something like this:

home_names_list_1 = []
home_names_list_2 = []
for i in range(100):
    home_names_list_1.append("home" + str(i))

for i in range(100,200):
    home_names_list_2.append("home" + str(i))

for file in files:
    moved = False
    for name in home_names_list_1:
        if file.startswith(name):
            print("move somewhere")
            moved = True
            break
    if moved:
        break
    
    for name in home_names_list_2:
        if file.startswith(name):
            print("move somewhere else")
            break
    
    print(" did not move because did not match anything")
    
Answered By: Itération 122442

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...
Answered By: Ivo Ribeiro
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.