如何基于file_type动态调用Pandas读取函数并精简重复代码
优化方案
先直接上优化后的代码,再拆解优化思路:
import pandas as pd import numpy as np def file_to_df(file_name, fields=None, file_type=None, encoding=None): """Read stock level from csv or xlsx file.Filter SKU and Qty.Return dataframe.""" # 用字典映射文件类型到对应读取函数,替代嵌套if-elif reader_map = { 'csv': pd.read_csv, 'xls': pd.read_excel } # 校验文件类型合法性 if file_type not in reader_map: print('no csv or xls filetype was handed to file_to_df') return None # 返回None让调用方可以做后续判断,比只打印更实用 # 定义所有读取函数的公共参数 common_params = { 'filepath_or_buffer': file_name, 'converters': {'Barcode': str, 'Qty': int}, 'usecols': fields } # 根据文件类型添加专属参数 if file_type == 'csv': common_params['encoding'] = encoding # 动态调用读取函数并传入参数 data_frame = reader_map[file_type](**common_params) # 空行清理逻辑(修复原代码里的np_nan拼写错误) data_frame.replace('', np.nan, inplace=True) data_frame.dropna(axis=0, how='any', subset=None, inplace=True) return data_frame
关键优化点说明
- 动态切换读取函数:用
reader_map字典做类型与函数的映射,后续要支持新格式(比如xlsx),只需要在字典里加一行'xlsx': pd.read_excel即可,扩展性拉满,彻底摆脱嵌套判断的冗余。 - 动态调整参数:先提取公共参数统一维护,再根据文件类型追加专属参数(比如csv的
encoding),避免重复写参数列表,后续参数变更只需要修改一处。 - 修复原代码bug:
- 原代码
if file_type == 'csv' or 'xls'逻辑错误,会导致任何file_type都会进入分支,改成file_type in reader_map更严谨。 - 修正了
np_nan的拼写错误,应为np.nan。
- 原代码
- 提升实用性:非法类型时返回
None,调用方可以通过返回值判断是否读取成功,比只打印提示更友好。
内容的提问来源于stack exchange,提问作者zoni
相关产品推荐
相关产品推荐

