简体   繁体   中英

ImportError: cannot import name in python

I'm trying to create python modules for business analytics. I created these python files:

  1. main file
  2. export_to_csv (for saving data into file)
  3. stationarity (for stationarity test and differencing)

The files are located in the same folder.

The code in 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:

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

The general syntax to import and call a function from a separate file from same directory:

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.

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

from stats.function_file import function_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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