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

标签 python

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

我想从 Main.py 调用一个变量并将值写入一个名为“tempFile.txt”的新文件。我尝试导入“Main.py”,但出现属性错误。

这是“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

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

编辑:

主.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 创建后,这些值确实出现了.py 并取消注释 File1.py 中的 write 函数

最佳答案

您提供的代码创建了循环导入;即 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)

文件1.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

关于python - 如何从另一个文件调用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40536035/

相关文章:

c# - 从 C# 调用 Python 方法(没有 IronPython)

python - Django 通过列表中的值从数据库中查找项目?

python - 在Python中进行winsorize但忽略nan的正确方法

python - 在 Python 中将字符串转换为数字

python - Spark 创建数据帧,其中包含整数和 float 混合的列

python - 在 Python 中根据 JSON 架构过滤 JSON 数据

Python 字符串格式化 - 为同一个参数组合命名占位符和浮点格式化程序?

python - 带有 color_mode 的 keras ImageDataGenerator.flow

python - 如何将不对称误差线添加到 Pandas 分组条形图?

python - Python 的 argparse 可以像 gnu getopt 一样置换参数顺序吗?