文件模式匹配变量与正则表达式



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

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

unmapped_FUND1_20180203_20180204.CSV

我猜正则表达式会是一个很好的用途吗?

你可以试试join

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.

最新更新