【问题标题】:How can I use the calling file loop variable in another file (python)如何在另一个文件中使用调用文件循环变量(python)
【发布时间】:2019-08-01 06:50:37
【问题描述】:

所以,我有文件 ma​​in.py

PB_array=['2019-01-01','2019-02-01','2019-03-01','2019-04-01']
for PB in PB_array:
    import anotherfile 

另一个文件.py

Filename=f"file-{PB}.tsv"
some functions...

如何在另一个文件中使用变量“PB”?

【问题讨论】:

  • 目前尚不清楚您的最终目标是什么,但最好从anotherfile 导入函数并以PB 作为参数调用它们。

标签: python variables import


【解决方案1】:

在循环中调用import 是没有意义的。导入将只进行一次。您似乎误解了 python 中 import 语句的目的。它不是像 bash 这样的 POSIX shell 中的source 命令的模拟。解决方法是将模块 anotherfile.py 中的代码放入函数或类方法中。然后从 for PB in PB_array: 循环体中调用该函数(或方法)并将 PB 作为参数传递给函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-16
    • 2013-01-12
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多