-2

I am trying the following code in python

def fixPdf(pdfFile):
    try:
        fileOpen = file(pdfFile, "a")
        fileOpen.write("%%EOF")
        fileOpen.close()
        return "Fixed"
    except:
        return "Unable to open file: %s with error: %s" % (pdfFile, str(e))

if __name__ == '__main__':
    fixPdf('Sample.pdf')

I got the error NameError: name 'e' is not defined. How can I define this variable in the exception part of the code?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
YasserKhalil
  • 9,138
  • 7
  • 36
  • 95

1 Answers1

2

If the intent is for e to be the exception, you need to assign it to that name as part of the except:

def fixPdf(pdfFile):
    try:
        fileOpen = file(pdfFile, "a")
        fileOpen.write("%%EOF")
        fileOpen.close()
        print("Fixed")
    except Exception as e:
        print(f"Unable to open file: {pdfFile} with error: {e}")
        
if __name__ == '__main__':
    fixPdf('Sample.pdf')

You also need to print the messages if you want them to be visible, since the caller does not print the return value of the function.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Thank you very much. I got now an error `Unable to open file: Sample.pdf with error: name 'file' is not defined` – YasserKhalil Sep 03 '21 at 17:26
  • 1
    Sounds like you haven't defined or imported whatever this `file` thing is that's supposed to open the PDF file. Maybe you meant to use the `open` function? – Samwise Sep 03 '21 at 17:29
  • Thanks a lot. It works now but when manually open the pdf after executing the code, I received a message to save the file. Can I save the pdf file with the same code? – YasserKhalil Sep 03 '21 at 17:44
  • 1
    Debugging the PDF formatting and/your PDF viewer is out of my wheelhouse, unfortunately :\ – Samwise Sep 03 '21 at 18:29