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脚本中的最后一行并失败,因为如果文件不存在,则前一个函数调用没有输出。

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])
添加回答
举报