Add line number to Text File

Published on June 28, 2021

In this snippet, I'm going write a small python file which can help you to add the line infront of the senteces in text file. We need to do text procecessing in Natural Language Processing (NLP), sometimes It cause an errors from one or two sentence in the text file. Somehow we cannot figure out which sentence that make us streess :). In this small Python File, I will try to write a flexible way to add line number to any file you want. Please check the code below.

#!/usr/bin/env python

"""Adding Line Number To Every Sentences"""

__author__      = "Khem Puthea"
__copyright__   = "Copyright 2021, puthea.khem@gmail.com"

import sys
filename = sys.argv[-1]

original = open(filename, 'r')
addLine = open('WithLineNumber' +filename + '', 'w')

count = 000000
while True:
    count +=1
    line = original.readline()
    if not line:
        break
    addLine.writelines(str(count) + '\t' + line.rstrip() +'\n')
original.close()
addLine.close()

Please share this post, if it's hepful.

About Me

I am a full-stack Laravel developer based in Phnom Penh, Cambodia.. I'm also the creator of Rean Code.

My passions are open-source, managing software , and creating quality and maintainable products.

Follow me on Twitter: @putheakhem.

© Khem Puthea