NameError:name' writer'没有定义

时间:2017-10-15 21:06:53

标签: python function parameter-passing local-variables nameerror

def create_and_update_worksheets():
    """
    Add 'Player statistics' if the worksheet is not in file_name. 
    Otherwise, it will update the worksheet itself.
    """

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    writer = pd.ExcelWriter(file_name, engine='openpyxl')
    row = 0

    for item in worksheets['Game Schedule'].values():
        multiple_dfs(item, 'Game Schedule')

    for sheet in writer.sheets.values():
        resize_columns(sheet)

    writer.save()
    writer.close()

在这个实际代码中,writerrow已经定义,但如果我决定实施multiple_dfs,我会收到一些错误:

def multiple_dfs(item, sheets):
    """
    Put multiple dataframes into one xlsx sheet
    """

    response = send_request(item).content
    df = pd.read_csv(io.StringIO(response.decode('utf-8')))

    df.to_excel(writer, sheets, startrow=row, index=False)
    row = row + len(df) + 2

我为writer收到了以下错误,但row发生了同样的事情。

Traceback (most recent call last):
  File "create_and_update_xlsx_sheets.py", line 66, in <module>
    create_and_update_worksheets()
  File "create_and_update_xlsx_sheets.py", line 56, in create_and_update_worksheets
    multiple_dfs(item, 'Game Schedule')
  File "create_and_update_xlsx_sheets.py", line 33, in multiple_dfs
    df.to_excel(writer, sheets, startrow=row, index=False)
NameError: name 'writer' is not defined

我该如何解决这些错误?我不想在multiple_dfs中重新定义它们,但我还需要在将来的功能中重新定义它们。

1 个答案:

答案 0 :(得分:1)

即使您从writer存在的作用域调用该函数,被调用者也看不到它,这就是python的作用域规则的工作原理。

我建议您的multiple_dfs函数接受另一个名为writer的参数,您可以从调用函数传递该参数。如果除writer之外还有多个参数要传递,则需要使用变量参数。

def multiple_dfs(item, sheets, *args):
    for i, var in enumerate(args, 1):
        print('variable {}: {}'.format(i, var))
    ...

致电multiple_dfs

multiple_dfs(item, 'Game Schedule', variable1, variable2, ...)