猿问

将输入作为变量存储在函数中,然后在另一个函数中调用该变量

我正在学习 Python 3,但在编写程序时遇到了困难。


我正在尝试编写一些代码来读取文件,然后打印出其文本的一部分。这是我到目前为止所拥有的。


def greeting():

    """Print a message when the program starts."""

    greeting = "Welcome to the file reader."

    greeting += "\nEnter the name of the file you would like to read. "

    greeting += "If the file is in a different folder, type the file path."

    greeting += "\n(Type 'exit' to quit, or 'help' for help.) "

    file_name = input(greeting)



def read_file():

    """Search for the file, then read it line by line. Print an error if the file isn't found."""

    try:

        with open(file_name) as f_obj:

            file_contents = f_obj.readlines()

            print(file_name + " was opened successfully")

    except FileNotFoundError:

        print("Error: File not found.")



greeting()

read_file()

print(file_contents[:9])

当我运行此代码时,我输入了一个文件名(同一目录中的文本文件的),然后出现此错误。


Traceback (most recent call last):

  File "reader.py", line 21, in <module>

    read_file()

  File "reader.py", line 13, in read_file

    with open(file_name) as f_obj:

NameError: name 'file_name' is not defined

所以我的问题是,如何将用户输入正确存储在一个函数中,然后在另一个函数中调用它?


PIPIONE
浏览 168回答 2
2回答

长风秋雁

您想要做的不是将输入存储在函数的本地范围内(这是违反直觉的),因为您需要其他地方的数据(其他函数)。您应该从greeting()函数中返回数据,以便它可以用于其他逻辑,如下所示:def greeting():&nbsp; &nbsp; """Print a message when the program starts."""&nbsp; &nbsp; greeting = "Welcome to the file reader."&nbsp; &nbsp; greeting += "\nEnter the name of the file you would like to read. "&nbsp; &nbsp; greeting += "If the file is in a different folder, type the file path."&nbsp; &nbsp; greeting += "\n(Type 'exit' to quit, or 'help' for help.) "&nbsp; &nbsp; file_name = input(greeting)&nbsp; &nbsp; return file_name&nbsp; # Return user inputdef read_file(file_name):&nbsp; &nbsp; """Search for the file, then read it line by line. Print an error if the file isn't found."""&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; with open(file_name) as f_obj:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file_contents = f_obj.readlines()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(file_name + " was opened successfully")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return file_contents&nbsp; # Return the contents of the file&nbsp; &nbsp; except FileNotFoundError:&nbsp; &nbsp; &nbsp; &nbsp; print("Error: File not found.")input_file_name = greeting()output_file_contents = read_file(input_file_name)print(output_file_contents[:9])注意:如果找不到文件,此代码将出现问题。它将到达print脚本中的最后一行并失败,因为如果文件不存在,则前一个函数调用没有输出。

HUH函数

def greeting():&nbsp; &nbsp; """Print a message when the program starts."""&nbsp; &nbsp; greeting = "Welcome to the file reader."&nbsp; &nbsp; greeting += "\nEnter the name of the file you would like to read. "&nbsp; &nbsp; greeting += "If the file is in a different folder, type the file path."&nbsp; &nbsp; greeting += "\n(Type 'exit' to quit, or 'help' for help.) "&nbsp; &nbsp; return input(greeting)def read_file(file_name):&nbsp; &nbsp; """Search for the file, then read it line by line. Print an error if the file isn't found."""&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; with open(file_name) as f_obj:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file_contents = f_obj.readlines()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(file_name + " was opened successfully")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return file_contents&nbsp;&nbsp; &nbsp; except FileNotFoundError:&nbsp; &nbsp; &nbsp; &nbsp; print("Error: File not found.")print(read_file(greeting())[:9])
随时随地看视频慕课网APP

相关分类

Python
我要回答