python - 定义一个函数并将其用于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 文件?
解决方案
如果您需要在其他 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)
一般来说,您应该在单独的文件中定义常用函数,并将其导入到您需要这些函数的每个文件中。
推荐阅读
- java - 包含 1 个元素的数组是否占用与该 1 个元素相同的内存量?
- java - SetHasFixedSizetrue 显示错误 如何解决
- javascript - JavaScript 减去 reactJS 中使用的时间
- .net - 如何解决错误.net framework version were not found?
- c# - OpenTK:将 unifrorm 数组和 vec2d 传递给片段着色器
- python - 在另一个数据框中搜索数据框列
- c# - EFCore 迁移是否应该提交给版本控制?
- html - 如何修复不显示的子菜单?
- arrays - 更快地清除包含大量数据的二维数组
- python - 如何在逻辑回归中使用计算的阈值?