Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading