Search code examples
pythoncomputer-visionopencvpython-tesseract

Finding latest file in directory


I'm trying to get the latest .png file created in a directory: output_folder_one. Once find pass that file to cv2 and pytessercat to print the captured text. However, I keep getting this error:

AttributeError: 'str' object has no attribute 'png'

could someone help me understand what's going on?

Code:

import cv2
import pytesseract
import os
import glob

LatestFile = max(glob.iglob('output_folder_one'.png) , key=os.path.getctime)

image = cv2.imread(LatestFile)

test = pytesseract.image_to_string(image)

print(test)

Any insight would be greatly appreciated!


Solution

  • The AttributeError means you are trying to access an attribute that don't existing for the object. in your case .png in the following string 'output_folder_one'.png.

    You have to change it as: 'output_folder_one/*.png' where:

    • The string contains the path to the directory to analyze. In your case output_folder_one
    • The * means to get all the file
    • The .png after the * means to get all the file with the specific extension.
    import os
    import glob
    
    LatestFile = max(glob.iglob('output_folder_one/*.png') , key=os.path.getctime)
    
    print(LatestFile)
    #OUTPUT: 'output_folder_one'.png (my last file)