gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:10:06 28 4
gpt4 key购买 nike

我正在学习 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

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

最佳答案

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

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

关于python - 将输入存储为函数中的变量,然后在另一个函数中调用该变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947410/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com