Home > OS >  python: check if a specific string is part of a filename
python: check if a specific string is part of a filename

Time:12-03

I have a list, where each entry consists of 5 individual random numbers:

List-output:

...
['00349']
['02300']
['00020']
...

Now I have two nested for loops. The outer loop iterates over this list. The inner loop iterates over a buch of files which are located in a separate directory. The aim is that I want to check each entry in the list if the number is contained in one of the filenames. If so, I want to copy these files into a separate target directory and break the inner loop because the item was found and continue with the next entry in the list.

Structure of a file example:

name_01043.json

I tried several things (see below) but the following version returns always false.

Here is my code so far:

from re import search
import fnmatch

list = []

# some code to fill the list

SOURCE_PATH = "dir/source"
TARGET_PATH = "dir/target"

for item in list:
    for fname in os.listdir(SOURCE_PATH):
        # check if fname contains item name:
        strg1 = str(fname)
        strg2 = str(item)
        if fnmatch.fnmatch(fname, strg2):
        # if fnmatch.fnmatch(fname, '*'   strg2   '*'):
            sourcepath = os.path.join(SOURCE_PATH, fname)
            shutil.copy(sourcepath, TARGET_PATH)
            break

CodePudding user response:

You can use something like this:

for path, subdirs, files in os.walk(SOURCE_PATH):
    for file in files:
        if strg2 in str(file):
            # Do something

This for will return each path, subdirectory and file from the location. You can check file by file this way and simply check if the str(file) contains the string you need

CodePudding user response:

Here's an example where you could make good use of the glob module:

import glob
import os
import shutil

SOURCE_PATH = 'dir/source'
TARGET_PATH = 'dir/target'
# just use some hard-coded values for the sake of example
mylist = ['00349', '02300', '00020']

for e in mylist:
  for file in glob.glob(os.path.join(SOURCE_PATH, f'*{e}*')):
    shutil.copy(file, TARGET_PATH)
  • Related