我正试图阻止此代码给我关于我创建的名为beloved.txt的文件的错误,我使用FillNotFoundError:表示不给我错误,并打印未找到的文件,而是打印该文件消息和错误消息。我该如何解决?
def count_words(Filenames):
with open(Filenames) as fill_object:
contentInFill = fill_object.read()
words = contentInFill.rsplit()
word_length = len(words)
print("The file " + Filename + " has " + str(word_length) + " words.")
try:
Filenames = open("beloved.txt", mode="rb")
data = Filenames.read()
return data
except FileNotFoundError as err:
print("Cant find the file name")
Filenames = ["anna.txt", "gatsby.txt", "don_quixote.txt", "beloved.txt", "mockingbird.txt"]
for Filename in Filenames:
count_words(Filename)
答案 0 :(得分:0)
一些提示:
class
名称之外,不要大写变量。Filenames = open("beloved.txt", mode="rb")
,现在您要重新分配它再次表示不同的意思 !!这种行为会导致头痛... 该脚本的主要问题是试图在try
语句之外打开文件。您只需将代码移到try:
内即可!当您不使用except FileNotFoundError as err:
时,我也不太了解err
。在这种情况下,您应该将其重写为except FileNotFoundError:
:)
def count_words(file):
try:
with open(file) as fill_object:
contentInFill = fill_object.read()
words = contentInFill.rsplit()
word_length = len(words)
print("The file " + file + " has " + str(word_length) + " words.")
with open("beloved.txt", mode="rb") as other_file:
data = other_file.read()
return data
except FileNotFoundError:
print("Cant find the file name")
filenames = ["anna.txt", "gatsby.txt", "don_quixote.txt", "beloved.txt", "mockingbird.txt"]
for filename in filenames:
count_words(filename)
我也不明白为什么从同一个文件中读取数据而不考虑您向函数输入的return data
为何拥有函数file
的原因?在所有情况下,您都将获得相同的结果……
答案 1 :(得分:0)
“使用open(Filenames)作为fill_objec:”语句将引发异常。 因此,您至少必须将该语句包含在try部分中。在您的代码中,您首先会得到len,然后检查特定文件beloved.txt。这个加倍的代码使您可以复制重复的月经。建议:
def count_words(Filenames):
try:
with open(Filenames) as fill_object:
contentInFill = fill_object.read()
words = contentInFill.rsplit()
word_length = len(words)
print("The file " + Filename + " has " + str(word_length) + " words.")
except FileNotFoundError as err:
print("Cant find the file name")