简体   繁体   中英

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?

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.

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")
    

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...

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