如何使用python中的用户定义模块(类似于库的另一个文件)中使用的exec()?

2024-04-24 03:43:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法从另一个使用exec使变量动态的文件导入模块

但是,我在exec函数中使用了globals()方法来访问变量,并得到了期望的结果(能够访问变量)

class ad:   

    def read(self):

        root = tk.Tk()
        root.withdraw()

        filepath = filedialog.askopenfilenames()

        dfList = []

        for name in range(1, len(filepath)+1):
            dfList.append("df"+str(name))

        counter = 0
        for i in tqdm(range(len(filepath))):
            file_type = os.path.basename(str(filepath[i]))
            file_type_ext = os.path.splitext(file_type)

            if file_type_ext[-1] == '.csv':
                exec("%s=pd.read_csv(%s)" % (dfList[counter], "'"+filepath[i]+"'"), globals())
                counter += 1

obj = ad()

obj.read()

但是当我试图将这个文件(用户定义模块)导入另一个文件时,它就是不起作用!他们有什么解决方案,我可以像导入库一样导入这个文件吗


Tags: 模块文件nameinforreadtypecounter