-1

I am getting a syntax error in a try suite on a variable created within the try suite. Is it not correct to call a variable in the except suite that was created in the try suite? This is the only reason I could think of that there would be a syntax error for that variable.

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')

The syntax error is appearing on the variable 'file_name' in the last line

Thanks

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358

2 Answers2

0

Python does not support this kind syntax, you should use:

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))

For Python 3.6:

print(f'The file \'{file_name}\'doesn\'nt exist')
Ke Li
  • 942
  • 6
  • 12
  • I am certain I have used that exact print syntax in Python 3.6. Its my main way to print. – juggy_crisp Mar 23 '17 at 01:39
  • @juggy_crisp: It's only valid with string literals. Non-literal expressions need to be composed into the string properly, either with formatting/interpolation or with concatenation. – Ignacio Vazquez-Abrams Mar 23 '17 at 01:46
0

You could also use string concatenation in:

print("The file" + " " + file_name + " " + "doesn\'t exist")
Richard Ackon
  • 651
  • 1
  • 7
  • 11