Except Suite

时间:2017-03-23 01:24:00

标签: python except

我在try套件中创建的变量的try套件中出现语法错误。在try套件中创建的except套件中调用变量是不正确的?这是我能想到该变量会出现语法错误的唯一原因。

try:
 file_name = input('Enter the encrypted file: ')
 encryptionKey = open(input('Enter the file name for theencryptionkey: '),'r')
 anEncryptedLine = open(file_name)
 decrypted_file = open(decrypted_file.txt,'a+')
 decrypted_str = ''
 for i in decrypted_file:
    decrptyed_line =substitutionDecrypt(i)
    print(decrypted_line, file=decrypted_file.txt)

except IOError:
 print('The file 'file_name'doesn\'nt exist')

语法错误出现在变量' file_name'在最后一行

谢谢

2 个答案:

答案 0 :(得分:0)

Python不支持这种语法,您应该使用:

try:
    file_name = input('Enter the encrypted file: ')
    encryptionKey = open(input('Enter the file name for theencryptionkey: '),'r')
    anEncryptedLine = open(file_name)
    decrypted_file = open(decrypted_file.txt,'a+')
    decrypted_str = ''
    for i in decrypted_file:
       decrptyed_line =substitutionDecrypt(i)
       print(decrypted_line, file=decrypted_file.txt)
except IOError:
    print('The file \'%s\'doesn\'nt exist' % file_name)
    # or print('The file \'{}\'doesn\'nt exist'.format(file_name))

对于Python 3.6:

print(f'The file \'{file_name}\'doesn\'nt exist')

答案 1 :(得分:0)

您还可以在:

中使用字符串连接
print("The file" + " " + file_name + " " + "doesn\'t exist")