繁体   English   中英

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

[英]Calling a variable from another function inside another file

我正在尝试将字典变量从 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")

在我的新 python 文件中,我试图带上字典。

Python 文件 B.py

import csv
from A import load

print(codedict)

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

我认为这会有所帮助:

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})  

B.py

import csv
from A import load
codedict = load("Dataforcars.cvs")
print(codedict)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM