我正在尝试定义一个函数,它应该打开具有给定名称的文件,在屏幕上显示其内容,一次三个字符,然后关闭文件。如果使用无效的文件名调用此版本函数,则该函数应该崩溃。但是,我认为我的代码中存在一个错误,导致它在没有运行该函数的情况下崩溃。
到目前为止,这是我的代码:
def trigram_printer(filename):
"""str -> none"""
print("Please enter a filename: ")
filename = input("> ")
while True:
try:
file = open(filename)
for line in file:
print(line)
file.close()
break
except IOError:
print("There was a problem accessing file '" + filename + "'." + \
"Please enter a different filename.")
filename = input(">")
对于错误消息,我实际上得到了"访问文件时出现问题'" + filename +"'。" + "请输入不同的文件名。" ...所以我认为它可能至少有一点工作。如果你能帮助我......
答案 0 :(得分:0)
您正在覆盖传递给函数的文件名参数,并且您要求用户输入文件名,因此根本不需要。
正如heifzhan所提到的,你不应该使用文件,因为它是内置的,但在Python 3中不是问题。 See here
关于你的任务,我会:
以下是我的例子:
def trigram_printer2():
"""str -> none"""
print("Please enter a filename: ")
filename = input("> ")
try:
opened_file = open(filename)
three_chars = opened_file.read(3)
while three_chars != "":
three_chars = opened_file.read(3)
print (three_chars)
opened_file.close()
except IOError:
print("There was a problem accessing file '" + filename + "'." + \
"Please enter a different filename.")
答案 1 :(得分:-1)
你必须缩进所有功能体。
def trigram_printer(filename):
"""str -> none"""
print("Please enter a filename: ")
filename = input("> ")
while True:
try:
file = open(filename)
for line in file:
print(line)
file.close()
break
except IOError:
print("There was a problem accessing file '" + filename + "'." + \
"Please enter a different filename.")
filename = input(">")