Python 使用正则表达式匹配变量的文件模式

Python 使用正则表达式匹配变量的文件模式,python,regex,Python,Regex,我在弄清楚如何弄清楚这个文件模式时遇到了很多麻烦。我有以下代码: def file_pattern_match(self, fundCode, startDate, endDate): # check if the fundcode is in the array or if the fundcode matches one in the array fundCode = fundCode if fundCode in self.fundCodes else 'Invalid_

我在弄清楚如何弄清楚这个文件模式时遇到了很多麻烦。我有以下代码:

def file_pattern_match(self, fundCode, startDate, endDate):

    # check if the fundcode is in the array or if the fundcode matches one in the array
    fundCode = fundCode if fundCode in self.fundCodes else 'Invalid_Fund_Code'

    # set a file pattern
    file_pattern = 'unmapped_{fund}_{start}_{end}.csv'.format(fund=fundCode, start=startDate, end=endDate) 

    # look in the unmappedDir and see if there's a file with that name

    # if the there is load the positions
    pass
这是一个属于类的函数。有一个问题。我刚刚意识到参数
fundCode
实际上是一个值数组,所以我需要使用某种分隔符。最后,我想查找与这种模式匹配的文件:

unmapped_FUND1_FUND2_FUNDETC_20180203_20180204.CSV

unmap\u FUND1\u 20180203\u 20180204.CSV


我猜正则表达式对此很有用?

您可以尝试
加入

fundCode_raw = ['FUND1','FUND2','FUNDETC']
fundCode_str = '_'.join(fundCode_raw)

>> fundCode_str
'FUND1_FUND2_FUNDETC'

您不应该只需要正则表达式来查看是否存在具有该名称的文件。您只需构造要查找的文件名(使用适当的路径),然后测试它是否存在

import os
path = "unmappedDir/unmapped_{fund}_{start}_{end}.csv".format(fund = "_".join(fundCode), start = startDate, end = endDate)
if os.path.isfile(path):
    # Do loading.