pythonfile-writingline-count

How to write the line count at top of the file after the lines are written in that file?


Can someone tell me how to write the line count on top of the file after the lines are written in that file using python?

line_count=?

sam
john
gus
heisenberg

Solution

  • Here ya go!

    text = open("textfile.txt").readlines()
    counter = 0
    for row in text:
        counter += 1  # just snags the total amount of rows
    
    newtext = open("textfile.txt","w")
    newtext.write(f"line_count = {counter}\n\n") # This is your header xoxo
    for row in text:
        newtext.write(row) # put all of the original lines back
    newtext.close()
    

    Make sure you put in the paths to the text file but this short script will just tack on that line_count = Number header that you wanted. Cheers!