如何从另一个文件中调用变量?

时间:2016-11-10 20:00:05

标签: python

我有两个文件。第一个文件,我们称之为“Main.py”。第二个是“file1.py”。

我想从Main.py调用一个变量,并将值写入名为“tempFile.txt”的新文件。我尝试导入“Main.py”但是我收到了Attritbute错误。

以下是“File1.py”

的示例
import os
import sys
import main

 # This function should write the values from Main.py to a tempFile 

 # and reads the contents to store into a list.

def writeValues():

    tempFile = open('tempFile.txt', 'w+')        
    tempFile.write(str(X_Value))
    tempFile.write("\n")
    tempFile.write(str(Y_Value))
    zoneValues = [line.rstrip('\n') for line in open('tempFile.txt')]
    print zoneValues

 # X_Value and Y_Value are the variables in Main.py I am trying to access



def readZoneValues(): # Creates a list from values in tempFile.txt
    valuesList = [line.rstrip('\n') for line in open('tempFile.txt')]
    print valuesList

我尝试过其他人寻找答案,但对这个具体问题没有明确答案。

修改

Main.py

 import os
 import sys
 import file1



 X_Value = 1000
 Y_Value = 1000



 # For statement that manipulates the values, too long to post.
 for "something":
     if "something":


 # after the values are calculated, kick it to the console
 print "X Value: " + str(X_Value) + "\n"
 print "Y Value: " + str(Y_Value) + "\n"

我需要在处理完Main.py之后将变量的值写入tempFile。

修改

我已经尝试过在Main.py中创建了tempFile,但由于某些原因,我的函数读取tempFile并将值添加到列表中,但是,在删除了Main中的tempFile创建后,值为DO APPEAR .py并取消注释File1.py

中的写入功能

2 个答案:

答案 0 :(得分:1)

您要呈现的代码会创建循环导入;即main.py导入file1.py和file1.py导入main.py.这不起作用。我建议更改write_values()以接受两个参数,然后从main.py传入它们,并取消将main导入到file1中:

main.py:

import os
import sys
import file1

X_Value = 1000
Y_Value = 1000

file1.writeValues(X_Value, Y_Value)

file1.py:

import os
import sys

# This function should write the values from Main.py to a tempFile 
# and reads the contents to store into a list.
def writeValues(X_Value, Y_Value):
    tempFile = open('tempFile.txt', 'w+')        
    tempFile.write(str(X_Value))
    tempFile.write("\n")
    tempFile.write(str(Y_Value))
    tempFile.close()
    zoneValues = [line.rstrip('\n') for line in open('tempBeds.txt')]
    print zoneValues

def readZoneValues(): # Creates a list from values in tempFile.txt
    valuesList = [line.rstrip('\n') for line in open('tempFile.txt')]
    print valuesList

答案 1 :(得分:0)

尝试导入它。

from YourFileName import *

此外,在致电时,

YourFileName.tempFile 

如果您只想调用您的变量,

from YourFileName import VarName1
相关问题