python - 使用python运行具有不同参数的函数
问题描述
我有想要使用不同参数运行的函数
这是目录结构:
App/
├─ main.py
└─ fcts1.py
└─ fcts2.py
└─ File1.csv
└─ File2.csv
└─ Files/
└─B.xlsx
└─A.txt
└─C.xlsx
经验 1:
file1 = "file1.csv"
from fcts1 import fct1
def A_fct(fileA):
df = pd.read_csv(file1)
dfA = pd.read_csv(fileA,skiprows=2,sep=r"\s*\|\s*")
fct1()
def B_fct(fileB):
df = pd.read_csv(file1)
dfB = pd.read_excel(fileB)
fct1()
def C_fct(fileC):
df = pd.read_csv(file1)
dfC = pd.read_excel(fileC)
fct1()
经验 2:
file2 = "file2.csv"
from fcts2 import fct1
def A_fct(fileA):
df = pd.read_csv(file2)
dfA = pd.read_csv(fileA,skiprows=2,sep=r"\s*\|\s*")
fct1()
def B_fct(fileB):
df = pd.read_csv(file2)
dfB = pd.read_excel(fileB)
fct1()
def C_fct(fileC):
df = pd.read_csv(file2)
dfC = pd.read_excel(fileC)
fct1()
NB1: fcts1.py 中的 fct1() 与 fcts2.py 中的 fct1() 不同
NB2:每个功能都执行特定的任务
我已经用关系 file_name => 函数定义了一个字典,因为我想读取文件名(A/B/C..)并为 Files 文件夹中的每个文件调用可调用函数
name_to_func = {
"A": A_fct,
"B": B_fct,
...
}
然后遍历文件夹中的文件,并调用该函数
import os
path = '/your/path/here'
name_to_func = {
"A": A_fct,
"B": B_fct
}
for file_name in os.listdir(path):
file_prefix = file_name.split('.')[0]
name_to_func[file_prefix](file_name)
有时我想使用和从文件 fcts1.py 运行这些函数,df = pd.read_excel(file1)
有时fct1()
使用
df = pd.read_excel(file2)
和fct1()
从文件 fcts2.py 运行这些函数,请问我该怎么做?
解决方案
您可以将这 6 个函数替换为一个:
def fct(file_number, file_letter, function):
# Key idea: you can pass functions as arguments
df = pd.read_excel(file_number)
dfA = pd.read_excel(file_letter)
function()
这可以这样调用:
import fcts1, fcts2
fct("file1.csv", whatever_file, fcts1.fct1)
fct("file2.csv", whatever_file, fcts2.fct1)
推荐阅读
- laravel - 我如何使用 vue js 和 laravel 在所见即所得编辑器中显示我的文章的正确格式
- javascript - 什么是 waapi 有效的 css 属性
- python - 如何比较两个不同 RDF 中的类
- sql-server-express - 对象“sp_sqlagent_update_agent_xps”、数据库“msdb”、模式“dbo”的执行权限被拒绝。[SQLSTATE 42000](错误 229)
- android - 在android中更改ShapeDrawable中的圆弧半径
- visual-studio-2017 - 如何在安装项目中更改桌面应用程序的安装路径?视觉工作室 2017
- html - 使用div时如何对齐单选按钮?
- ionic-framework - 无法通知依赖解析侦听器 - IONIC 4 Build
- java - 使用 Java JXL 库更改 Excel 工作表的选项卡颜色
- java - Android资源链接失败的值,styles.xml