首页 > 解决方案 > 如何从目录中读取文件并将其转换为表?

问题描述

我有一个接受位置参数(、、、和)的类startDate,我endDate有以下方法:unmappedDirfundCodes

下面的方法应该接受一个数组fundCodes并查看一个目录,看看它是否找到匹配某种格式的文件

def file_match(self, fundCodes):
    # Get a list of the files in the unmapped directory
    files = os.listdir(self.unmappedDir)

    # loop through all the files and search for matching fund code
    for check_fund in fundCodes:

        # set a file pattern
        file_match = '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
            return self.read_file(file_match)
        else:
            Logger.error('No file found with those dates/funds')

另一种方法只是应该从该文件创建一个 etl 表。

def read_file(self, filename):
    loadDir = Path(self.unmappedDir)
    for file in loadDir.iterdir():
        print('*' *40)
        Logger.info("Found a file : {}".format(filename))
        print(filename)
        unmapped_positions_table = etl.fromcsv(filename)
        print(unmapped_positions_table)
        print('*' * 40)
        return unmapped_positions_table

运行它时,我可以检索文件名:

Found a file : unmapped_positions_PUPSFF_2018-07-01_2018-07-11.csv unmapped_positions_PUPSFF_2018-07-01_2018-07-11.csv

但是在尝试创建表时,出现此错误:

FileNotFoundError: [Errno 2] No such file or directory: 'unmapped_positions_PUPSFF_2018-07-01_2018-07-11.csv'

它是否需要文件名的完整路径或其他内容?

标签: pythonoperating-system

解决方案


有了这个:

files = os.listdir(self.unmappedDir)

你得到的文件self.unmappedDir

因此,当您获得名称匹配时(生成您的名称时),您必须通过传递完整路径来读取文件(否则例程可能会检查当前目录中的文件):

return self.read_file(os.path.join(self.unmappedDir,file_match))

除了:在set这里使用:

files = set(os.listdir(self.unmappedDir))

因此文件名查找将比使用list

而且您的read_file方法(我之前没有看到)应该只打开文件,而不是再次扫描目录(并且无论如何在第一次迭代时返回,所以它没有意义):

def read_file(self, filepath):
    print('*' *40)
    Logger.info("Found a file : {}".format(filepath))
    print(filepath)
    unmapped_positions_table = etl.fromcsv(filepath)
    print(unmapped_positions_table)
    print('*' * 40)
    return unmapped_positions_table

或者,不要更改您的主要代码(set部分除外),并在目录名称之前添加,read_file因为它是一个实例方法,因此您可以方便地使用它。


推荐阅读