简体   繁体   English

ImportError:无法在 python 中导入名称

[英]ImportError: cannot import name in python

I'm trying to create python modules for business analytics.我正在尝试为业务分析创建 python 模块。 I created these python files:我创建了这些 python 文件:

  1. main file主文件
  2. export_to_csv (for saving data into file) export_to_csv(用于将数据保存到文件中)
  3. stationarity (for stationarity test and differencing)平稳性(用于平稳性测试和差分)

The files are located in the same folder.这些文件位于同一文件夹中。

The code in export_to_file: export_to_file 中的代码:

import json
import csv


def save_to_json(data: dict, title: str):
    with open(f"{title}.json", mode="w", encoding="UTF-8") as file:
        json.dump(data, file, indent=4, ensure_ascii=False)



def save_to_csv(data: dict, title: str, first_row: list):
    with open(title, "w", encoding="UTF-8", newline="") as file:
        writer = csv.writer(file, delimiter=";")
        writer.writerow(first_row)
    
    for var, val in data.item():
        with open(title, "a", encoding="UTF-8", newline="") as file:
            writer = csv.writer(file, delimiter=";")
            writer.writerow([var, *val])

When importing the module into my main file to use functions, python shows an import error:将模块导入到我的主文件中使用函数时,python 显示导入错误:

ImportError: cannot import name 'save_to_json' from 'export_to_file' (c:\Users\user\Desktop\123\python\export_to_file.py)

The main file code:主文件代码:

import openpyxl
import pandas as pd
from export_to_file import save_to_csv
from stationarity import stationarity_test


book = openpyxl.open(r"C:\Users\user\Desktop\123\data.xlsx")
sheet = book.active


# get data from table
data = {}
i = 0
for col in sheet.iter_cols(min_row=2, max_row=24, min_col=2, max_col=315):
    values = []
    for cell in col:
        if cell.value is None:
            values.append(0)
        else:
            values.append(cell.value) 
    values = pd.Series(values)
    var = values[0]
    data[var] = values[1:]
    i += 1


# stationarity test and differencing
pvalues, stationary_data = stationarity_test(data)

first_row_pvalue = ["variable", "p-value", "d1_p_value", "d2_p-value", "d3_p-value", "d4_p-value"]
first_row_data = ["years", 2000,    2001,   2002,   2003,   2004,   2005,   2006,   2007,   2008,   2009,   2010,   2011,   2012,   2013,   2014,   2015,   2016,   2017,   2018,   2019,   2020,   2021]
save_to_csv(pvalues, "stationarity.csv", first_row_pvalue)
save_to_csv(stationary_data, "stationary_data.csv", first_row_data)

The third file code:第三个文件代码:

import pandas as pd
from statsmodels.tsa.stattools import adfuller


# differencing
def difference(dataset, interval=1):
    diff = list()
    for i in range(interval, len(dataset)):
        value = dataset[i] - dataset[i - interval]
        value = pd.Series(value)
        diff.append(value)
    return diff


# function removing 0 from the beginning and end in dataset
def clear_zeros(dataset):
    for i in dataset:
        if i == 0:
            dataset = dataset[1:]
        else:
            break
    for i in dataset[::-1]:
        if i == 0:
            dataset = dataset[:-1:]
        else:
            break
    return dataset


# check stationarity
# if non-stationary => differencing
def stationarity_test(data):
    data_pvalues = {}
    data_stationary = {}

    for var, val in data.items():
        v = clear_zeros(val)
        res = adfuller(v, maxlag=0)
        stationary_data = [var, *val]
        
        res2 = [0, None]
        res3 = [0, None]
        res4 = [0, None]
        res5 = [0, None]

        if res[1] > 0.05:
            d1val = difference(v)
            res2 = adfuller(d1val, maxlag=0)
            var = var + "1"
            stationary_data = [var, 0, *d1val]
            if res2[1] > 0.05:
                d2val = difference(d1val)
                res3 = adfuller(d2val, maxlag=0) 
                var = var[:-1:] + "2"
                stationary_data = [var, 0, 0, *d2val]
                if res3[1] > 0.05:
                    d3val = difference(d2val)
                    res4 = adfuller(d3val, maxlag=0)
                    var = var[:-1:] + "3"
                    stationary_data = [var, 0, 0, 0, *d3val]
                    if res4[1] > 0.05:
                        d4val = difference(d3val)
                        res5 = adfuller(d4val, maxlag=0)
                        var = var[:-1:] + "4"
                        stationary_data = [var, 0, 0, 0, 0, *d4val]
                    
        pvalues = [var, res[1], res2[1], res3[1], res4[1], res5[1]]

        data_pvalues[pvalues[0]] = pvalues[1:]
        data_stationary[stationary_data[0]] = stationary_data[1:]
    
    return data_pvalues, data_stationary  

I tried to do the following:我尝试执行以下操作:

  1. Changed places of importing files, second file has the same problem修改了导入文件的位置,第二个文件也有同样的问题
  2. Remove pandas from all files, but it didn't help从所有文件中删除 pandas,但没有帮助
  3. Googled and it says that maybe it was a spelling mistake, or a circular dependency.用谷歌搜索,它说可能是拼写错误或循环依赖。 The spelling is correct, and I couldn't find a circular dependency.拼写正确,我找不到循环依赖。

What you are doing is correct just that the name of the file is wrong in main.py correct it and code will work fine你所做的是正确的,只是文件名在 main.py 中是错误的,更正它并且代码可以正常工作

The general syntax to import and call a function from a separate file from same directory:从同一目录的单独文件导入和调用 function 的一般语法:

main.py:主要文件:

from function_file import function_name

function_name(arguments)

function_file.py would be the file which will have function_name method defined within. function_file.py 将是其中定义了 function_name 方法的文件。

NOTE: when you use folders to keep your code then you need use folder name eg stats is my folder where function_file.py is stored then注意:当您使用文件夹来保存代码时,您需要使用文件夹名称,例如 stats 是我的文件夹,然后存储 function_file.py

from stats.function_file import function_name

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

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