pythonpython-3.xshutilpython-osfnmatch

Python: If filename in specified path contains string, then move to folder


New to python here. I would like to create a script that will scan my directory and if the filename contains a certain string in it, then it will automatically move to a folder of my choice. Have tried this, but to no luck:

import os
import shutil
import fnmatch
import glob

ffe_path = 'E:/FFE'
new_path = 'E:/FFE/Membership/letters'
keyword = 'membership'


os.chdir('E:/FFE/Membership')
os.mkdir('letters')



source_dir = 'E:/FFE'
dest_dir = 'E:/FFE/Membership/letters'

os.chdir(source_dir)

for top, dirs, files in os.walk(source_dir):
    for filename in files:
        if not filename.endswith('.docx'):
            continue
        file_path = os.path.join(top, filename)
        with open(file_path, 'r') as f:
            if '*membership' in f.read():
                shutil.move(file_path, os.path.join(dest_dir, filename))

Any insight would be greatly appreciated.


Solution

  • A simple function will do the trick:

    def copyCertainFiles(source_folder, dest_folder, string_to_match, file_type=None):
        # Check all files in source_folder
        for filename in os.listdir(source_folder):
            # Move the file if the filename contains the string to match
            if file_type == None:
                if string_to_match in filename:
                    shutil.move(os.path.join(source_folder, filename), dest_folder)
    
            # Check if the keyword and the file type both match
            elif isinstance(file_type, str):
                if string_to_match in filename and file_type in filename:
                    shutil.move(os.path.join(source_folder, filename), dest_folder)
    

    source_folder = full/relative path of source folder

    dest_folder = full/relative path of destination folder (will need to be created beforehand)

    string_to_match = a string basis which the files will be copied

    file_type (optional) = if only a particular file type should be moved.

    You can, of course make this function even better, by having arguments for ignoring case, automatically creating a destination folder if it does not exist, copying all files of a particular filetype if no keyword is specified and so on. Furthermore, you can also use regexes to match filetypes, which will be far more flexible.