运行它时提示我一条错误消息

时间:2019-11-06 19:26:27

标签: python

我有这个程序,应该如何工作,但是有1个小问题,我真的不知道该怎么办。我想解决必须重新格式化整个程序的问题。在while循环的最开始。我创建了一个with语句,该语句执行程序应该执行的操作。该程序将打开一个文件,进行读取,然后输出一个文本文件中有多少个唯一的单词。 with语句可以工作,但是现在with语句之后的错误检查无法执行,并提示我一个错误。当您输入一个不存在的文件时,应该提示用户说“文件(文件名)不存在!”。但是,with语句之后的代码将不再执行,并且系统会提示FileNotFoundError。

    def FileCheck(fn):
    try:
        open(fn, "r")
        return 1
    except IOError:
        print("The file " + filename + " was not found!")
        return 0

loop = 'y'
while loop == 'y':
    filename = input("Enter the name of the file you wish to process?: ")
    with open(filename, "r") as file:
        lines = file.read().splitlines()
        uniques = set()
        for line in lines:
            uniques = set(line.split())
            print("There are " + str(len(uniques)) + " unique words in " + filename + ".")
    if FileCheck(filename) == 1:
        loop = 'n'
    else:
        exit_or_continue = input("Enter the name of the file you wish to process or type exit to quit: ")
        if exit_or_continue == 'exit':
            print("Thanks for using the program!")
            loop = 'n'
        else:
            break

这是我输入不存在的文件时的错误消息

Enter the name of the file you wish to process?: aonsd.txt
Traceback (most recent call last):
  File "C:/Users/C/PycharmProjects", line 21, in <module>
    with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'aonsd.txt'

1 个答案:

答案 0 :(得分:0)

您的问题在这里是逻辑问题:

filename = input("Enter the name of the file you wish to process?: ")
with open(filename, "r") as file:
    ...
if FileCheck(filename) == 1:

您非常清楚地输入了文件名,然后尝试打开它,而不必费心检查它的存在。直到完成读取文件,您才进行检查。

您在书面说明中表达的逻辑暗示您想要

filename = input("Enter the name of the file you wish to process?: ")
if FileCheck(filename):
    with open(filename, "r") as file:
        ...