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

时间:2019-03-01 15:14:20

标签: python python-3.x

我正在学习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 个答案:

答案 0 :(得分:2)

您要执行的操作不是将输入存储在函数的本地范围内(这是很直观的),因为您需要在其他位置(其他函数)中的数据。

您应该从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行,并失败,因为如果文件不存在,则前一个函数调用将没有输出。

答案 1 :(得分:0)


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