首页 > 解决方案 > 定义一个函数并将其用于python中的多个文件或模块

问题描述

如何创建一个函数来格式化可用于多个 python 文件或模块的 excel 文件。我可以理解变量的问题。我期待 python 从主文件中加载变量。

我已经定义了一个函数来格式化 Excel 表。当我在同一个模块上使用它时它工作正常。但是,我希望该功能可用于多个文件。

我用过下面的代码

#my function in a file myfunction

def myformatfunction():

    workbook = writer.book
    worksheet = writer.sheets['report']

    total_fmt = workbook.add_format({'align': 'right', 'num_format': '$#,##0',
                                 'bold': True, 'bottom':6})

    worksheet.set_column('A:F', 20)
    worksheet.set_column('G:G', 20, total_fmt)

    writer.save()

#this is my main file where i want to use defined function
# i have dataframe which will read excel file

writer = pd.ExcelWriter('E:/FunctionOut2.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='report')


myformatfunction()

当我在同一个模块上使用它时,这工作正常。如何将它用于多个 python 文件?

标签: pythonexcelpython-3.6

解决方案


如果您需要在其他 Python 文件中使用相同的函数,您可以在不同的文件中定义它并导入该文件。例如,您可以在与您想使用它的文件相同的目录中创建一个名为“utils.py”的文件,并在那里定义您的函数。不过,最有可能的是,您要使用该功能的文件并不都在同一个目录中。您可以将 utils.py 放在所有这些都可以访问的更高目录中,或者将 utils.py 所在的目录添加到 Python 查找导入模块的路径中。

例如:

src/utils/utils.py

def myfunction(parameters):
    # you'll also need params if you want to call if for different dataframes
    (...)
    return

src/files/file1.py(您将在其中调用该函数)

import sys
sys.path.append("src/utils") # this includes src/utils to the list of paths where python will look for the modules you want to import
from utils import * # or import myfunction only

(...)
myfunction(df)

一般来说,您应该在单独的文件中定义常用函数,并将其导入到您需要这些函数的每个文件中。


推荐阅读