为什么此try-except打印错误消息?

时间:2020-03-28 22:17:24

标签: python io

这是我的代码:(我刚刚复制并粘贴了它。)

import sys

i = 0
files = ["untitled.kov", "coronavirus.py"]

def file_valid(filename):
    if filename[-4] == "." and filename[-3] == "k" and filename[-3] == "o" and filename[-1] == "v":
        return True

def create_file(file):
    try:
        if file[-4] == "." and file[-3] == "k" and file[-3] == "o" and file[-1] == "v":
            nf = open(file, "w")
    except:
        file = file + ".kov"
    finally:
        is_first_line = True
        while True:
            line = input("Line? (Type 'q' to quit.")
            if line == "q":
                nf.close()
                sys.exit()
            else:
                if is_first_line == False:
                    line = line + "\n"
                    nf.write(line)
                else:
                    nf.write(line)
                    is_first_line = False

i = 1
for file in files:
    print("Option " + str(i) + ": " + file)
    i = i + 1                                                                       
print("DISCLAIMER: Some files will not be in this list, but are avaliable.")
print("See this program's project folder to view a complete list of files.")

while True: 
    content = None

    filename = input("Which file would you like? (Type 'q' to quit.) ")

    try:       
        if file_valid(filename):
            f = open(filename, "r")
            content = f.read().splitlines()
    except FileNotFoundError:
        print("Sorry, that file doesn't exist.")
        # if input("Create it? (y/n)") == "y":   - Not sure if this is valid..
            new_filename = input("What would you like the file to be called?")
            create_file(new_filename)                                                              
        else:
            print("Sure!")
            print("Remember, you can always add a file into the program folder!")
    except:
        if filename == "q":
           sys.exit()
        else:
            print("Sorry, something went wrong.")
    else:
        try:
            for line in content:
                i = i + 1
                print("Line " + str(i) + ": " + line)
            content.close()   
        except TypeError:
            print("Sorry, something went wrong.")

我正试图说“抱歉,该文件不存在”。 (...)如果是扩展名为.kov的文件,但始终只说“对不起,出了点问题。”

此外,在“ if input()...”部分中,该代码是否有效? 我想知道我的代码是否过于复杂以及如何解决。

2 个答案:

答案 0 :(得分:1)

来自open()的文档:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

except FileNotFoundError:替换为except OSError:,它将起作用。

顺便说一下,您可以通过以下方式检查filename的扩展名为.kov:

if filename.endswith(".kov"):
# your logic

关于if input()...-有效。

答案 1 :(得分:0)

我解决了!首先,我删除了第一个“对不起,出了点问题”。它是父except块。然后,我将退出检查移至底部的except TypeError块。我还更改了if file[-4] == "." and file[-3] == "k" and file[-3] == "o" and file[-1] == "v":块以使用endswith()