为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PIPIONE 2021-11-23 16:41:44
我正在学习 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所以我的问题是,如何将用户输入正确存储在一个函数中,然后在另一个函数中调用它?
查看完整描述

2 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

您想要做的不是将输入存储在函数的本地范围内(这是违反直觉的),因为您需要其他地方的数据(其他函数)。


您应该从greeting()函数中返回数据,以便它可以用于其他逻辑,如下所示:


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)

    return file_name  # Return user input



def read_file(file_name):

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

            return file_contents  # Return the contents of the file

    except FileNotFoundError:

        print("Error: File not found.")



input_file_name = greeting()

output_file_contents = read_file(input_file_name)

print(output_file_contents[:9])

注意:如果找不到文件,此代码将出现问题。它将到达print脚本中的最后一行并失败,因为如果文件不存在,则前一个函数调用没有输出。


查看完整回答
反对 回复 2021-11-23
?
HUH函数

TA贡献1836条经验 获得超4个赞

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.) "

    return input(greeting)



def read_file(file_name):

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

            return file_contents 

    except FileNotFoundError:

        print("Error: File not found.")





print(read_file(greeting())[:9])


查看完整回答
反对 回复 2021-11-23
  • 2 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信