Как правильно использовать рейз? - PullRequest
0 голосов
/ 14 февраля 2019

Может кто-нибудь помочь мне получить какую-то структуру в этом коде?Я новичок в этом.Ошибки должны фиксировать как несуществующие файлы, так и файлы, которые не содержат строк из четырех частей, разделенных знаком «;».

Программа должна выглядеть примерно так:

Имя теста -file: hejsan
"Это привело к ошибке ввода / вывода, пожалуйста, попробуйте еще раз!"

Имя файла викторины: namn.csv
"Файл имеет неправильный формат.должно быть четыре строки, разделенных; в каждой строке файла. "

Имя файла викторины: quiz.csv

Где quiz.csv выполняет все требования!

def get_quiz_list_handle_exceptions():
    success = True
    while success:
        try:

            file = input("Name of quiz-file: ")
            file2 = open(file,'r')

            for lines in range(0,9):
                quiz_line = file2.readline()
                quiz_line.split(";")

                if len(quiz_line) != 4:
                    raise Exception

    except FileNotFoundError as error:
        print("That resulted in an input/output error, please try again!", error)

    except Exception:
        print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")

    else:
    success = False


get_quiz_list_handle_exceptions()

Ответы [ 2 ]

0 голосов
/ 14 февраля 2019

У вас есть множество проблем:

  1. Неудачный правильный отступ в нескольких местах
  2. Невозможно сохранить результаты split, поэтому ваш тест длины проверяет длину строки,не число компонентов, разделенных точкой с запятой
  3. (Незначительный) Не используется оператор with и не закрывается файл, поэтому дескриптор файла можно оставить открытым на неопределенное время (зависит от интерпретатора Python)

Фиксированный код:

def get_quiz_list_handle_exceptions():
    success = True
    while success:
        try:

            file = input("Name of quiz-file: ")
            with open(file,'r') as file2:  # Use with statement to guarantee file is closed
                for lines in range(0,9):
                    quiz_line = file2.readline()
                    quiz_line = quiz_line.split(";")

                    if len(quiz_line) != 4:
                        raise Exception

        # All your excepts/elses were insufficiently indented to match the try
        except FileNotFoundError as error:
            print("That resulted in an input/output error, please try again!", error)

        except Exception:
            print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")
        else:
            success = False  # Fixed indent


get_quiz_list_handle_exceptions()
0 голосов
/ 14 февраля 2019

В вашем коде есть ошибка отступа

def get_quiz_list_handle_exceptions():
success = True
while success:
    try:

        file = input("Name of quiz-file: ")
        file2 = open(file,'r')

        for lines in range(0,9):
            quiz_line = file2.readline()
            quiz_line.split(";")

            if len(quiz_line) != 4:
                raise Exception

    except FileNotFoundError as error:
        print("That resulted in an input/output error, please try again!", error)

    except Exception:
        print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")
    else:
        success = False


get_quiz_list_handle_exceptions()
...