源代码
https://github.com/ma0513207162/PyPrecip。pyprecip\reading\read_api.py 路径下。
项目简介
PyPrecip 是一个专注于气候数据处理的 Python 库,旨在为用户提供方便、高效的气候数据处理和分析工具。该库致力于处理各种气候数据,并特别关注于降水数据的处理和分析。
导入相关库
在这里,读取 csv 和 excel 文件分别使用 csv 库和 openpyxl 库。utits 路径下是笔者自定义的一些工具函数,在源码中可以找到。
import os, csv
from openpyxl import load_workbook
from ..utits.except_ import RaiseException as exc
from ..utits.warn_ import RaiseWarn as warn
from ..utits.sundries import check_param_type
__file_exists 装饰器
一个简易的 python 装饰器 __file_exists,用于检测 path 参数有无正常输入,否则抛出自定义异常。
def __file_exists(func):
def wrapper(*args, **kwargs):
if not args and not kwargs:
exc.raise_exception("The file path is required.", TypeError)
return func(*args, **kwargs)
return wrapper
函数的签名和注释
- 以 read_csv 函数为示例,定义了一些必要的参数。
- by_row 参数表示是否按行读取数据。
- 其中 row_indices 和 column_indices 参数为 tuple 类型时,表示指定行索引或列索引。指定为 list 类型时,表示指定行范围或列范围。
- check_param_type 函数负责检查参数的类型。
@__file_exists
def read_csv(path: str, by_row: bool = False,
row_indices: (tuple|list) = (), column_indices: (tuple|list) = ()):
"""
Reads data for specified rows and columns from a CSV file.
Parameters:
- path: indicates the path of the CSV file
- row_indices: Specifies the read row range (list length 2) or row index (tuple)
- column_indices: specifies the read column range (list length 2) or column index (tuple)
- by_row: If True, read the file by rows (default). If False, read the file by columns.
Returns:
- Dictionary. The key indicates the file name and the value indicates the read data
"""
# 检查参数类型
check_param_type(path, str, "path");
check_param_type(row_indices, (tuple|list), "row_indices");
check_param_type(column_indices, (tuple|list), "column_indices");
主要功能的实现
根据传入的 row_indices 和 column_indices 参数搭配 zip 函数进行行列的转换, 使用切片和索引操作从原始 CSV 数据中提取指定的行列数据区域。这里最大的特点就是避免了使用大量的 for 循环进行同样功能的实现。
read_csv_result: dict =