如何在 python 中将列表转换为 glob 样式模式
How to convert the list to glob style pattern in python
我需要使用具有特定模式的 shutil copytree 复制文件。我作为列表的模式。我使用下面的方法将列表转换为字符串以传入复制树 ignore_pattern,如下所示。
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))
如果我硬编码模式如下
copytree(sourcedir, target_dir,ignore=ignore_patterns('*.bat','*.jar'))
工作正常,这里我无法重复模式,因为首先 运行 它将创建文件夹。所以我需要将列表转换为 glob 模式,以便它可以作为参数传递。但不知道如何将列表转换为全局模式。
如何实现?
编辑:
aa = ['*.bat','*.txt']
print(convert_list_to_str(aa))
结果:
'*.bat','*.txt'
您不需要 list_to_str 函数。当它在文档中说 ignore_patterns(*patterns)
时,这意味着该函数采用零个或多个参数。所以你需要这样称呼它:
copytree(sourcedir, target_dir,ignore=ignore_patterns(*pattern))
注意模式前的 *
,它将您的列表转换为一系列参数。
您可以在 python 此处阅读有关解包运算符的更多信息:https://codeyarns.com/2012/04/26/unpack-operator-in-python/
我需要使用具有特定模式的 shutil copytree 复制文件。我作为列表的模式。我使用下面的方法将列表转换为字符串以传入复制树 ignore_pattern,如下所示。
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))
如果我硬编码模式如下
copytree(sourcedir, target_dir,ignore=ignore_patterns('*.bat','*.jar'))
工作正常,这里我无法重复模式,因为首先 运行 它将创建文件夹。所以我需要将列表转换为 glob 模式,以便它可以作为参数传递。但不知道如何将列表转换为全局模式。
如何实现?
编辑:
aa = ['*.bat','*.txt']
print(convert_list_to_str(aa))
结果:
'*.bat','*.txt'
您不需要 list_to_str 函数。当它在文档中说 ignore_patterns(*patterns)
时,这意味着该函数采用零个或多个参数。所以你需要这样称呼它:
copytree(sourcedir, target_dir,ignore=ignore_patterns(*pattern))
注意模式前的 *
,它将您的列表转换为一系列参数。
您可以在 python 此处阅读有关解包运算符的更多信息:https://codeyarns.com/2012/04/26/unpack-operator-in-python/