Skip to content
Advertisement

create a csv with the Items missing on the latest file

I am trying to create a csv with the Items missing on the latest file log. the comparing files are out.csv wish is a scan result, and the latest csv on the log folder. the idea will be not repeating the rows already used before as the out.csv will have always the full content

import os
import csv
import time 
import glob
 
list_of_files = glob.glob('./log/*.csv')
latest_file = max(list_of_files, key=os.path.getctime)
previous_file = max(list_of_files, key=os.path.getctime)
vurious = datetime.now().strftime("%Y_%m_%d-%I:%M:%S_%p")+".csv"
    
with open(latest_file, 'r') as t1, open('out.csv', 'r') as t2:
        fileone = t1.readlines()
        filetwo = t2.readlines()

with open('./log/'+vurious, 'w') as mail:
        for line in filetwo:
            if line not in fileone:
                mail.write(line)
            else:
                print("nothing to email")

I have not a clue why it never show a consistent result I wonder if some one can help me with this thanks a lot.

Advertisement

Answer

As you are using ‘w’ as mode, this overrides any previous content in the new file for every iteration.

Try the folowing solution, that writes all the rows at once:

with open('./log/'+vurious, 'w') as mail:
    l=[line for line in filetwo if line not in fileone]
    if len(l)==0:
        print("nothing to email")
    else:
        mail.writelines(l)
            
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement