Python:如何导入包含另一个函数的函数

2024-05-07 08:27:41 发布

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

我有一个名为data_extraction的文件,它有两个函数get_data_from_dbdata_sanity,其中data_sanity调用get_data_from_db。当我试图在第二个文件中导入数据提取时,我得到一个错误

ImportError: cannot import name 'data_sanity' from 'data_extraction'

第二个文件

from data_extraction import get_data_from_db
from data_extraction import data_sanity

数据提取文件

def get_data_from_db(db_query, fileName):
    try:  
        (user, password) = creds()

        conn = database_config(user=user, password=password, database="*", port="*", host="*")

        def create_pandas_table(sql_query, database = conn):
            table = read_sql_tmpfile(sql_query, database)
            return table
        import tempfile

        def read_sql_tmpfile(query, conn):
            print("")
            with tempfile.TemporaryFile() as tmpfile:
                copy_sql = "COPY ({query}) TO STDOUT WITH CSV {head}".format(
                   query=query, head="HEADER"
                )
                cur = conn.cursor()
                cur.copy_expert(copy_sql, tmpfile)
                tmpfile.seek(0)
                df = pd.read_csv(tmpfile)

                return df

        conn.close()

    except (Exception, psycopg2.Error) as error :
        print("Error while connecting to the database:", error)

    sub_info.to_csv(f'{fileName}.csv', index=False)
    
    df = pd.read_csv(f'{fileName}.csv')
    
    return df

def data_sanity(model_loan_df):
    db_query = ("""
            select
                *
            from
                fdj.fdknfkdn
            """)          
    raw_loan_df = get_data_from_db(db_query, 'raw_loan_check_data')
    
    return model_loan_df.shape[0] ==  raw_loan_df.shape[0]


Tags: 文件csvfromdfdbsqldataget
1条回答
网友
1楼 · 发布于 2024-05-07 08:27:41

我想这应该行得通,至少在我的机器上行得通:

from data_extraction import *

它不起作用的原因可能是它们不在同一个目录中

相关问题 更多 >