pythonwildcardglobfnmatch

How to loop list in fnmatch


I am trying to move files from current directory to directory named 'python' in current directory if they are found in a list called 'file'. With the result that the file named '1245' will remain in same directory. I am trying to use fnmatch to match pattern so that all files that are contain 123 in their name can be moved.

import fnmatch
import os
import shutil
list_of_files_in_directory = ['1234', '1245', '1236', 'abc']
file = ['123', 'abc']


for f in os.listdir('.'):
    if fnmatch.fnmatch(f, file):
        shutil.move(f, 'python')

this throws following error: TypeError: expected str, bytes or os.PathLike object, not list

for f in os.listdir('.'):
    if fnmatch.fnmatch(f, file+'*'):
        shutil.move(f, 'python')

this throws following error TypeError: can only concatenate list (not "str") to list


Solution

  • file is a list, you can't pass that as the pattern to fnmatch.

    I'm guessing you want something like

    for f in os.listdir('.'):
        if any(fnmatch.fnmatch(f, pat+'*') for pat in file):
            shutil.move(f, 'python')
    

    though arguably file should probably be renamed to something like patterns.