Python 从另一个文件中的另一个函数调用变量

Python 从另一个文件中的另一个函数调用变量,python,Python,我正在尝试将一个字典变量从a.py中的函数导入到我的新python文件B.py中。然而,它似乎并没有带来它。codedict是我要导入的变量 Python文件A.py import csv def load(filename): with open(filename, 'r') as datafile: reader = csv.reader(datafile) next(reader) global codedict

我正在尝试将一个字典变量从a.py中的函数导入到我的新python文件B.py中。然而,它似乎并没有带来它。codedict是我要导入的变量

Python文件A.py

import csv

def load(filename):
    with open(filename, 'r') as datafile:  
        reader = csv.reader(datafile)    
        next(reader)
        global codedict
        codedict = sorted({k[1].lower() for k in reader})   
load("Dataforcars.cvs")
import csv
from A import load

print(codedict)
在我的新python文件中,我试图带上字典

Python文件B.py

import csv

def load(filename):
    with open(filename, 'r') as datafile:  
        reader = csv.reader(datafile)    
        next(reader)
        global codedict
        codedict = sorted({k[1].lower() for k in reader})   
load("Dataforcars.cvs")
import csv
from A import load

print(codedict)

但是,B.py中没有定义“codedict”

Codedict是局部变量,您应该返回它,而不是尝试直接访问它。

我认为这将有助于:

A.py

import csv

def load(filename):
    with open(filename, 'r') as datafile:  
        reader = csv.reader(datafile)    
        next(reader)
        return sorted({k[1].lower() for k in reader})  
import csv
from A import load
codedict = load("Dataforcars.cvs")
print(codedict)
B.py

import csv

def load(filename):
    with open(filename, 'r') as datafile:  
        reader = csv.reader(datafile)    
        next(reader)
        return sorted({k[1].lower() for k in reader})  
import csv
from A import load
codedict = load("Dataforcars.cvs")
print(codedict)

我建议您阅读python中OOP的基础知识。您在使用它时犯了一个很大的错误。@Prashant Kumar您好,谢谢您的回复。我将尝试阅读更多关于它的内容,但是,你能解释一下我不正确使用它的地方吗?你应该删除
A.py
中的
global codedict
。谢谢你这样做了!现在我明白了.csv文件没有出现,因为它不在我在B.py中调用的函数的范围内。如果我试图通过在变量下使用return codedict返回codedict。那么低于回报率的一切都不会起作用,这是真的。你应该总是把return放在函数的末尾。谢谢,我把returncodedict放在函数的末尾。然后在CC7052的帮助下,我设法打电话给它。