python - 使用 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
某种方式重新编写它之外,我还能如何改进该方法。任何建议,将不胜感激。
解决方案
我最终将其重写为:
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))
推荐阅读
- java - 如何从 Spring 服务访问私有方法?
- python-3.x - 如何将 Postman OAuth 2.0 转换为 Python
- angular - 通过 http 解析使用接口和 Observable 时出错
- mysql - 无法使用两个表创建触发器
- raku - 如何区分 nqp 迭代器的类型
- bash - Bash - 遍历 INI 部分
- javascript - Chrome 扩展:如何从包含的 JS 脚本文件中记录某些内容
- ruby-on-rails - Rails - 单击其主要类别时显示菜单
- netbeans - Netbeans 10 - 自定义语法检查器 - 产生异常
- android - 将数据从 Firebase 检索到回收站视图时,文本字段为空