How can I get the number of lines of a text file before and after it is changed

Viewed 41

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.log and read the number of lines in it and store in another file line_count.txt

  • If the line_count.txt does not exist OR its size is 0 that means sample.log is being read for the first time(before appending), so open line_count.txt and add the count of number of lines of sample.log to it.

  • If log file is read after appending, read line_count.txt and 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?

1 Answers

when you re using os.system(cmd) it's just execute the command cat file.txt and print the content of the file on the console but it returns 0 so prev_lc will be always equal to 0 instead of using this command try to open the file and read the first line. Another thing is when you open a file with w mode and write in you remove all file previous content instead use a here is a suggestion for the code:

prev_lc=0
lc_now=0
with open('sample.txt', 'r') as myfile:
    lc_now=len(myfile.readlines())

with open("line_count.txt", 'r') as myfile1:
        file_lines=myfile1.readlines()
        if file_lines:
          prev_lc=file_lines[-1]
        else:
          prev_lc=0 
with open("line_count.txt","a") as f       
        f.write(str(lc_now)+'\n')

return [prev_lc, lc_now]
Related