0

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

1 Answers1

2

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thank you it worked. Now I want to use a file which contains data (names of files) that can be used as list as in line 5 in the question ```import fnmatch, os, shutil list_of_files_in_directory = ['1234', '1245', '1236', 'abc'] file = ['123', 'abc']``` How do I use the file as a list (I don't want to put the name of files to be moved in the python code as it would just look bad). – bc210405165 JAWAD MANSOOR Mar 15 '22 at 07:00
  • 1
    That seems like a topic for a separate question. As you can see, attempting to post code in comments is basically useless. Do you mean you want to read the patterns from a text file? `with open(filename, "r") as patternfile: patterns = patternfile.readlines()` – tripleee Mar 15 '22 at 07:04
  • I understand your point. I can't understand code easily here. Ok, I will make a new question. – bc210405165 JAWAD MANSOOR Mar 15 '22 at 07:06