如何在基于人脸的考勤中为每一天创建一个单独的 CSV 文件,而不是覆盖现有的

问题描述

在此代码中,出勤率被标记在“attendance.csv”文件中。我想要的是每天创建单独的“attendance.csv”,而不是覆盖现有文件,以便我可以在将来出现员工冲突时追溯过去的出勤情况。 我无法思考和实现它是如何实现的。

出勤 CSV 文件包含以下条目:

ID,NAME,ATTENDANCE,EMAIL
12,sk,1,sk12@gmail.com
15,aratrika Kosta,ak15@gmail.com

编程语言使用 Python。

def marking():
    df = pd.read_csv("CSV_files//attendance.csv")
   # df.loc[:,"ATTENDANCE"] = 0 # default attendance value (absent)
   # df.to_csv("CSV_files//attendance.csv",mode = 'w',index=False)

    def assure_path_exists(path): #if path not exists create path
        dir = os.path.dirname(path)
        if not os.path.exists(dir):
            os.makedirs(dir)

    
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    assure_path_exists("trainer/")
    recognizer.read('trainer/trainer.yml')
    cascadePath = "haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(cascadePath);
    font = cv2.FONT_HERShey_SIMPLEX
    cam = cv2.VideoCapture(0)

    while True:
        # Read the video frame
        ret,im =cam.read()

        # Convert the captured frame into grayscale
        gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

        # Get all face from the video frame
        faces = faceCascade.detectMultiScale(gray,1.2,5)

        # For each face in faces
        for(x,y,w,h) in faces:

            # Create rectangle around the face
            cv2.rectangle(im,(x-20,y-20),(x+w+20,y+h+20),(0,255,0),4)

            # Recognize the face belongs to which ID
            Id,confidence = recognizer.predict(gray[y:y+h,x:x+w])
            
            
            print(confidence)
            #confidence-->0 (best),more the value of confidence lesser will be accuracy
            if confidence>80: 
                continue
            
            else:
                imgdict = dict()
                df = pd.read_csv("CSV_files//attendance.csv")
                #Names and Ids as imgdict
                diction = dict(df.loc[:,'ID']) #making dict from ID and NAME columns
                imgdict = {}
                for key,vals in diction.items():
                    imgdict[key+1] = vals

                # Check the ID if exist 
                for k,v in imgdict.items(): #looping through all keys
                    #print(k,type(k),v)
                    if (v==Id):
                        Id = v #if key is matched with recognizer Id,then assign Id=valueofimgdict
                        df = pd.read_csv("CSV_files//attendance.csv")
                        df.loc[k-1,"ATTENDANCE"]= 1  #student is present
                        # df.loc[:,"ATTENDANCE"]= 1  #student is present
                        df.to_csv("CSV_files//attendance.csv",index=False)
                         
                # Put text describe who is in the picture
                cv2.rectangle(im,(x-22,y-90),(x+w+22,y-22),-1) #-1-->filled rectangle
                cv2.putText(im,str(Id),(x,y-40),font,(255,255),3) #1 is size,3 is thickness

        # display the video frame with the bounded rectangle
        cv2.imshow('im',im) 

        # If 'q' is pressed,close program
        if cv2.waitKey(10) & 0xFF == ord('q'):
            break

    # Stop the camera
    cam.release()

    # Close all windows

    cv2.destroyAllWindows()

解决方法

导入

您需要导入 datetime 模块

import datetime

只需添加今天的日期

然后将日期与出勤名称合并,如下所示:

x = datetime.date.today()
path = 'CSV_files//attendance_{}.csv'.format(x.day)

path = f'CSV_files//attendance_{x.day}.csv'

现在,如果您打印此路径,则会显示以下内容:

print(path)

输出

CSV_files//attendance_4.csv

完整日期

path = f'CSV_files//attendance_{x.day}-{x.month}-{x.year}.csv'

输出

print(path)    
CSV_files//attendance_4-4-2021.csv