在目录中循环查找匹配的文件

2024-04-25 05:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模块,它遍历目录并找到匹配的文件,然后进行转换并发送电子邮件。模块采用以下命令参数:

startDateendDatefundCodes以及它将搜索的格式最终将是这样的:

citco_unmapped_positions_PUPSEN_2018-07-01_2018-07-09.csv

我目前的问题是,fundCodes参数将是一个基金数组:

['PUPSEN', 'POSUF', 'AGE']

导致以下方法出现问题:

def positions_file_search(self, fundCodes):
    # Get a list of the files
    files = set(os.listdir(self.unmappedDir))
    # loop through all the files and search for matching file
    for check_fund in fundCodes:
        # set a file pattern
        file_match = 'citco_unmapped_positions_{fund}_{start}_{end}.csv'.format(fund=check_fund, start=self.startDate, end=self.endDate)
        # look in the unmappeddir and see if there's a file with that name
        if file_match in files:
            # if there's a match, load unmapped positions as etl
            filename = os.path.join(self.unmappedDir, file_match)
            return self.read_file(filename)
        else:
            Logger.error('No file found with those dates/funds')

上述方法的问题是,一旦找到匹配的文件,它就会返回,而不会遍历其余的资金。你知道吗

我现在在我的__main__.py页面上这样称呼它:

unmapped_positions = alerter.positions_file_search(alerter.fundCodes) ... does something afterwards

这是可行的,但是,我需要找到一种方法,对每个基金进行相同的处理。你知道吗

注意:我不能这样做:

for fund in alerter.fund:
     alerter.positions_file_search(fund)
    etc...

因为每个基金的电子邮件格式都会重复。我需要改变我的方法。如有任何建议,将不胜感激。你知道吗


Tags: the方法inselfforsearch基金match
1条回答
网友
1楼 · 发布于 2024-04-25 05:28:26

您可以通过替换

return self.read_file(filename)

yield self.read_file(filename)

这将允许您编写:

for unmapped_positions in alerter.positions_file_search(alerter.fundCodes):
   ...

有关生成器的详细信息,请参见https://wiki.python.org/moin/Generators

相关问题 更多 >