Vishwesh Bhat
Vishwesh Bhat

Reputation: 64

Data in .csv file is being replaced instead of being appended

I am working on a attendance system using face recognition code. I wanted to save the face recognition output(Name of the recognized people) in a .csv file.

So, I tried this:

def Attendance(name):
    moment=time.strftime("%Y-%b-%d",time.localtime())
    open('Attendance'+moment+'.csv','w')
    with open ('Attendance'+moment+'.csv','a+',newline="\n") as f:
        DataList = f.readlines()
        knownNames = []
        for data in DataList:
            ent = data.split(',')
            knownNames.append(ent[0])
        if name not in knownNames:
            curr=_datetime.date.today()
            dt=curr.strftime('%d%m%Y_%H:%M:%S')
            f.writelines(f'\n{name}, {dt}, P'+'\n')

It creates a .csv file by date.

But the issue is - this function I created, makes new data replace the older data in the .csv file, instead of appending the newer data in the next lines.

I need to append new data and eliminate re-entry of already existing data.

Kindly help!

Regards,

Vishwesh V Bhat

Upvotes: 1

Views: 341

Answers (3)

Vishwesh Bhat
Vishwesh Bhat

Reputation: 64

Issue solved!

Mistake I was making was, I was opening the .csv with w mode. So everytime I run the code, even if the .csv created on that date existed already it would overwrite the newer data to the first row.

So I used if os.path.exists('Attend'+moment+'.csv'): This solved the issue.

Solution:

def Attendance(name):
    moment=time.strftime("%Y-%b-%d",time.localtime())
    if os.path.exists('Attend'+moment+'.csv'):
        with open('Attend'+moment+'.csv','r+',newline="\n") as f:
            DataList = f.readlines()
            knownNames = []
            for data in DataList:
                ent = data.split(',')
                knownNames.append(ent[0])
        with open('Attend'+moment+'.csv','a',newline="\n") as f:
            if name not in knownNames:
                curr=_datetime.date.today()
                dt=curr.strftime('%d%m%Y_%H:%M:%S')
                f.writelines(f'\n{name}, {dt}, P')
    else:
        open('Attend'+moment+'.csv','w')

Upvotes: 0

KetZoomer
KetZoomer

Reputation: 2915

You are opening the file in write mode. This overwrites your file. Remove that line and your code should work.

Fixed Code:

def Attendance(name):
    moment=time.strftime("%Y-%b-%d",time.localtime())
    with open ('Attendance'+moment+'.csv','a+',newline="\n") as f:
        DataList = f.readlines()
        knownNames = []
        for data in DataList:
            ent = data.split(',')
            knownNames.append(ent[0])
        if name not in knownNames:
            curr=datetime.date.today()
            dt=curr.strftime('%d%m%Y_%H:%M:%S')
            f.writelines(f'\n{name}, {dt}, P'+'\n')

Also, make sure to follow PEP 8. f-string can also help make your code more readable.

Fixed Code that follows PEP 8 and is cleaner:

def Attendance(name):
    moment = time.strftime("%Y-%b-%d",time.localtime())
    with open(f'Attendance{moment}.csv', 'a+') as f:
        knownNames = [data.split(',')[0] for data in f.readlines()]
        if name not in knownNames:
            dt = datetime.date.today().strftime('%d%m%Y_%H:%M:%S')
            print(f'\n{name}, {dt}, P', file=f)

Upvotes: 1

AmineBTG
AmineBTG

Reputation: 697

Use the opening mode 'a' for append:

with open("filename.csv", "a") as f:
   ...

Upvotes: 2

Related Questions