定义一个函数并将其用于 python 中的多个文件或模块
Define a function and use it for multiple files or modules in python
如何创建函数来格式化可用于多个 python 文件或模块的 excel 文件。我可以理解变量的问题。我期待 python 从主文件加载变量。
我定义了一个函数来格式化 excel sheet。当我在同一个模块上使用它时,它工作正常。但是,我希望该功能用于多个文件。
我用过下面的代码
#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)
一般来说,您应该在单独的文件中定义常用函数,然后将其导入到您需要这些函数的每个文件中。
如何创建函数来格式化可用于多个 python 文件或模块的 excel 文件。我可以理解变量的问题。我期待 python 从主文件加载变量。
我定义了一个函数来格式化 excel sheet。当我在同一个模块上使用它时,它工作正常。但是,我希望该功能用于多个文件。
我用过下面的代码
#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)
一般来说,您应该在单独的文件中定义常用函数,然后将其导入到您需要这些函数的每个文件中。