pythondesign-patternsglobcopytree

How to convert the list to glob style pattern in python


I need to copy the files using shutil copytree with certain pattern. The patterns I am having as list. I converted the list to string using below method to pass in the copy tree ignore_pattern as below.

def convert_list_to_str(pattern):
    patter = ','.join("'{0}'".format(x) for x in pattern)
    return patter

copytree(sourcedir, target_dir,ignore=ignore_patterns(pattr))

If I hard code the pattern as below

copytree(sourcedir, target_dir,ignore=ignore_patterns('*.bat','*.jar')) 

It is working fine, Here I cannot iterate the pattern because in first run it will create the folder. So I need to convert the list to glob pattern so that it can be passed as a parameter. But don't know how to convert the list to glob pattern.

How to achieve this?

EDIT:

aa = ['*.bat','*.txt']
print(convert_list_to_str(aa))

Result:

'*.bat','*.txt'

Solution

  • You don't need your list_to_str function. When it says ignore_patterns(*patterns) in the docs it means that the function takes zero or more arguments. So you need to call it like this:

    copytree(sourcedir, target_dir,ignore=ignore_patterns(*pattern))
    

    notice the * before pattern, it converts your list to a series of arguments.

    You can read more about the unpack operator(s) in python here: https://codeyarns.com/2012/04/26/unpack-operator-in-python/