Dan Dan - 23 days ago 7
Python Question

How can I call a variable from another file?

I have two files. The first file, we'll call it "Main.py". The second, "file1.py".

I want to be call a variable from Main.py and write the value to a new file called "tempFile.txt". I've tried importing "Main.py" but I get an Attritbute error.

Here's an example of "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


I've tried other looking for answers but there was no clear answer to this specific issue.

EDIT:

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"


I need the values of the variables to be written to the tempFile after Main.py has been processed.

EDIT:

I have tried having the tempFile created in Main.py, but for some reason my function for reading the tempFile and adding the values to a list do not appear, however, the values DO APPEAR after I delete the tempFile creation in Main.py and uncomment the write function in File1.py

Answer

The code you're presenting creates a circular import; i.e. main.py imports file1.py and file1.py imports main.py. That doesn't work. I would recommend changing write_values() to accept two parameters, and then passing them in from main.py, and eliminating the import of main into 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
Comments