python - 如何从目录中读取文件并将其转换为表?
问题描述
我有一个接受位置参数(、、、和)的类startDate
,我endDate
有以下方法:unmappedDir
fundCodes
下面的方法应该接受一个数组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'
它是否需要文件名的完整路径或其他内容?
解决方案
有了这个:
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
因为它是一个实例方法,因此您可以方便地使用它。
推荐阅读
- javascript - 有没有办法在单击某个链接时自动打开选项卡?
- javascript - 如何制作一个完整的可选择的?
- c - 动态分配的多维数组
- sql - 关于Oracle SQL的优化(分组)
- android-studio - android profiler 如何查看调用图表
- java - QueryDSL fetch 加入没有 groupby 的请求 GROUP BY
- python - 从字符串中删除重复的字母
- node.js - 如何使用 Bluebird 承诺修复“分页中未定义的响应”(@google-cloud)
- javascript - Firebase/数据库 + 径向 Btn + JS
- python - 在 Python/Selenium 中创建登录和注销循环