对该特定模式使用fnmatch

2024-04-19 22:15:41 发布

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

我正在尝试编写一个函数,用于查找特定目录并查找特定文件格式的匹配项

函数格式如下:

def file_pattern_match(self, fundCodes, startDate, endDate):

    # set a file pattern
    file_pattern = 'unmapped_{fund}_{start}_{end}.csv'.format(fund=somethinghere, 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

这就是我有点困惑的地方fundCodes将是一个基金代码数组。因此,此函数必须搜索目录中的文件,并查看是否存在匹配项

称之为:

file_pattern_match(['FUND1', 'FUND2', 'FUND3'], '20180203', '20180204')

应该找到如下文件:

unmapped_FUND1_20180203_20180204.csv

我曾考虑过使用正则表达式,但我不确定如何使用字符串数组


Tags: csvthe函数目录ifmatchstartfile
1条回答
网友
1楼 · 发布于 2024-04-19 22:15:41

假设您的函数需要返回一个数据帧,并且只有一个代码与您的函数看起来像的文件相匹配

import pandas as pd    
import os

def file_pattern_match(self, fundCodes, startDate, endDate):
    # Get a list of the files
    files = os.listdir(unmappeddir)
    # loop through the codes and chack if they are in the files
    for check_fund in fundCodes:
        # set a file pattern
        file_pattern = 'unmapped_{fund}_{start}_{end}.csv'.format(fund=check_fund, 
            start=startDate, end=endDate) 

        # look in the unmappeddir and see if there's a file with that name
        if file_pattern in files:
            return pd.read_csv(file_pattern)

相关问题 更多 >