首页 > 解决方案 > 使用 Pathlib 搜索匹配的文件?

问题描述

我有以下方法:

def file_search(self, fundCodes, type):
    funds_string = '_'.join(sorted(fundCodes))
    files = set(os.listdir(self.unmappedDir))
    file_match = 'citco_unmapped_{type}_{funds}_{start}_{end}.csv'.format(type=type, funds=funds_string, start=self.startDate, end=self.endDate)
    if file_match in files:
        filename = os.path.join(self.unmappedDir, file_match)
        return self.read_file(filename)
    else:
        Logger.error('No {type} file/s found for {funds}, between {start} and {end}'.format(type=type, funds=fundCodes,
                                                                                            start=self.startDate, end=self.endDate))

该方法是搜索与特定格式匹配的文件的模块的一部分。 fundCodes将是一个数组,文件的其余信息来自其初始化变量。

所以该方法会找到一个像这样的文件,如果它匹配格式:

citco_unmapped_trades_PCASPE_PUPSFF_2018-07-19_2018-07-20.csv

在我的目录中。

有人告诉我要研究pathlib模块,因为我可能对此进行了过度设计,但我不确定除了以pathlib某种方式重新编写它之外,我还能如何改进该方法。任何建议,将不胜感激。

标签: python

解决方案


我最终将其重写为:

def file_search(self, fundCodes, dataType):
    funds_string = '_'.join(sorted(fundCodes))
    file_match = 'citco_unmapped_{type}_{funds}_{start}_{end}.csv'.format(type=dataType, funds=funds_string,
                                                                          start=self.startDate, end=self.endDate)
    unmapped_file = Path(self.unmappedDir, file_match)
    if unmapped_file.exists():
        return self.read_file(unmapped_file)
    else:
        Logger.error('No {type} file/s found for {funds}, between {start} and {end}'.format(type=dataType, funds=fundCodes,
                                                                                            start=self.startDate, end=self.endDate))

推荐阅读