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
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
You can't do it quite that simply. A file is a sequence of bytes. You must first ensure that when you write all of those lines, that you write them to their final positions. The easiest way to do this is to "reserve" space for your line count when you first write the file. Much as you have done in your description, write the entire file, but keep "placeholder" room for the line count. For instance, if you have a maximum of 9999 lines in the file, then reserve four bytes for that count:
line_count=????
sam
john
gus
heisenberg
Once you finish writing all of the lines, then back up to the appropriate byte position in the file (bytes 11-14) with seek(11)
, and file.write()
the count, formatted to four characters.
I'm assuming that you already know how to write lines to a file, and how to format an integer. All you're missing is the basic logic and the seek
method.
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!
f.seek(0)
f.write("line_count = %s\n"%n)
f.close()
Where n is line count value