Home > Mobile >  NameError name os is not defined error in python
NameError name os is not defined error in python

Time:02-15

I have tried the import os option as suggested, however, it did not resolve the issue.Pls, advise on this.

 try:
    from PIL import Image
    import os
    from pathlib import Path
except ImportError:
    import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\admin\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'

def ocr_core(filename):
    
    import os.path
path = os.path.abspath(os.path.dirname(__file__))
print(ocr_core(os.path.join(path, 'images', 'ocr_example.png')))
       
  **Error Details**
path = os.path.abspath(os.path.dirname(__file__))
NameError: name 'os' is not defined

CodePudding user response:

The problem is that you’re trying to import os inside of the try block. The moment you get an error in the try block, it immediately jumps to the exception handler. So if PIL fails to load then it will completely skip over the rest of the imports.

In general you should only put the part of your code that can potentially raise an exception inside of the try block.

import os
from pathlib import Path
try:
    from PIL import Image
except ImportError:
    import Image

CodePudding user response:

Instead of

import os.path

Try

import os

Also please check the indentation in the first line.

If this does not work, Then please use 'import os' outside the try function.

  • Related