【问题标题】:Looping through a directory to find matching files遍历目录以查找匹配的文件
【发布时间】:2018-07-13 18:36:29
【问题描述】:

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

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...

因为每个基金都会重复电子邮件格式。我需要以某种方式修改我的方法。任何建议将不胜感激。

【问题讨论】:

    标签: python file loops iteration generator


    【解决方案1】:

    你可以通过替换

    将你的函数变成一个生成器
    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

    【讨论】:

    • 天哪,这太棒了。它非常接近我的需要,尽管在执行for 循环时它仍然重复相同的邮件格式。但我想我可以从这里得到它!
    猜你喜欢
    • 2018-03-17
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多