I want to get the number of lines in a file before and after it is appended and want to read the lines present only in that range(read only the lines that are appended to the file) Code explanation.
open the
sample.logand read the number of lines in it and store in another fileline_count.txtIf the
line_count.txtdoes not exist OR its size is 0 that meanssample.logis being read for the first time(before appending), so openline_count.txtand add the count of number of lines ofsample.logto it.If log file is read after appending, read
line_count.txtand get the previous value stored in it and replace that value with the new line count(no of lines in file after appending)This is my code, that I have come up with.
prev_lc=0 lc_now=0 with open('sample.txt', 'r') as myfile: lc_now=len(myfile.readlines()) if os.path.exists('line_count.txt') and os.stat('line_count.txt').st_size!=0: cmd="cat line_count.txt" prev_lc=os.system(cmd) with open("line_count.txt", 'w') as myfile1: myfile1.write(str(lc_now)) else: with open("line_count.txt", 'w') as myfile2: myfile2.write(str(lc_now)) return [prev_lc, lc_now]
But my function is not returning me correct values,
For example, if sample.log has 5 lines before and after it got appended, it has 10 lines, my code should return [5,10], it is only returning [0,10]
cat line_count.txt
5
line_count has only 1 value in it --> number of lines of the log file I feel like I have ended up complicating the whole code, how can I optimise it?