Как я могу добавить функции try/except в этот код?

Я все еще создаю этот код, где с помощью атаки по словарю я нахожу пароль, введенный пользователем. Однако я бы вставил некоторые элементы управления при вводе источника файла (например, когда я набираю источник несуществующего файла) и когда я открываю файл, но внутри нет слова, которое соответствует введенному паролю пользователем. Мой разум говорит мне, что я могу использовать инструкции как «Если, иначе, Элиф», но другие программисты говорят мне, что я мог бы использовать инструкции try, кроме инструкций.

Это код:

"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.

"""


def dictionary_attack(pass_to_be_hacked, source_file):

    try:


        txt_file = open(source_file , "r")

        for line in txt_file:

            new_line = line.strip('\n')


            if new_line == pass_to_be_hacked:

                print "\nThe password that you typed is : " + new_line + "\n"

    except(







print "Please, type a password: "

password_target = raw_input()


print "\nGood, now type the source of the file containing the words used for the attack: "

source_file = raw_input("\n")


dictionary_attack(password_target, source_file)

person HaCk81t    schedule 20.12.2016    source источник
comment
Вы должны отформатировать свой код.   -  person Mohammad Yusuf    schedule 20.12.2016
comment
И есть ли актуальный вопрос? Все, что вы на самом деле говорите, это то, что я делаю X, но некоторые люди говорят мне, что вместо этого я могу сделать Y...   -  person twalberg    schedule 20.12.2016


Ответы (1)


Вы можете указать это как исключение «Файл не существует», и после того, как вы откроете существующий файл, вы можете использовать оператор if, чтобы проверить, существует ли что-либо внутри файла на вашем пути:

"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.

"""
def dictionary_attack(pass_to_be_hacked, source_file):
    try:
        txt_file = open(source_file , "r")
        if os.stat( txt_file).st_size > 0: #check if file is empty
            for line in txt_file:
                new_line = line.strip('\n')
                if new_line == pass_to_be_hacked:
                    print("\nThe password that you typed is : " + new_line + "\n")
        else:
            print "Empty file!"

    except IOError:
        print "Error: File not found!"

print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)
person Inconnu    schedule 20.12.2016