Почему эта попытка - кроме печати неправильного сообщения? - PullRequest
0 голосов
/ 29 марта 2020

Вот мой код: (я просто скопировал и вставил его.)

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 ]

1 голос
/ 29 марта 2020

Из документов для 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()... - оно действительно.

0 голосов
/ 03 апреля 2020

Я решил это! Сначала я удалил первое «Извините, что-то пошло не так». и это родительский except блок. Затем я переместил проверку на выход в нижний блок except TypeError. Я также изменил блоки if file[-4] == "." and file[-3] == "k" and file[-3] == "o" and file[-1] == "v":, чтобы использовать endswith().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...