首页 > 解决方案 > 使用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 运行这些函数,请问我该怎么做?

标签: pythonpython-3.xpandasparameter-passingargparse

解决方案


您可以将这 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)

推荐阅读