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

时间:2019-06-13 08:41:54

标签: python-3.x

file1.py

token="asdsadkj"

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

file2.py

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

输出: asdsadkj

2 个答案:

答案 0 :(得分:1)

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

project
|-- file1.py
\-- file2.py
# file1.py
token = "asdsadkj"
# file2.py
from file1 import token

access = token
print(token)

答案 1 :(得分:0)

您可以只使用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)

有关更多详细信息,请参阅The import system。另外还有tutorial关于模块和软件包的信息。