我正在学习 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
所以我的问题是,如何将用户输入正确存储在一个函数中,然后在另一个函数中调用它?
长风秋雁
HUH函数
相关分类