如何在另一个 Python 文件 (Python3.7) 中使用一个 Python 文件中的变量数据



file1.py

token="asdsadkj"

现在我想在一个新的 python 文件中使用该令牌

file2.py

access=token      #data from file1.py
print(access)

输出:阿斯德萨德克

假设文件位于同一目录中,即

project
|-- file1.py
-- file2.py
# file1.py
token = "asdsadkj"
# file2.py
from file1 import token
access = token
print(token)

您可以使用import语句来导入它。在 python 中,任何扩展名为 .py 的文件都是可以导入的模块。您可以尝试:

from file1 import token
print(token)

# Wildcard imports (from <module> import *) should be avoided,
# as they make it unclear which names are present in the namespace,
# confusing both readers and many automated tools. See comment below.
from file1 import *
print(token)

import file1
print(file1.token)

有关更多详细信息,您可以参考导入系统。还有一个关于模块和包的教程。

最新更新