Skip to content Skip to sidebar Skip to footer

Adding Line Numbers To A File

I need to write the line numbers to an already existing text file in python 3. They have asked for the first 5 columns of the text file to contain a 4 digit line number followed by

Solution 1:

This prints to stdout the text pattern you describe:

withopen('/etc/passwd') as fp:
    for i, line inenumerate(fp):
        sys.stdout.write('%04d %s'%(i, line))

If you need to edit the file in place, or support multiple files, try using fileinput:

#!/usr/bin/pythonimport fileinput
import sys

for line in fileinput.input(inplace=True):
    sys.stdout.write('%04d %s'%(fileinput.filelineno(), line))

Solution 2:

#!/usr/bin/python
numberedfile = open("test.txt", "r")
numberedlist = numberedfile.readline()
i = 0forlinesin numberdlist:
    i = i+1print str(i) + '\t' + lines
numberdfile.close()

Solution 3:

deftext_lines(file):
    c = open(file, "r")
    list_of_lines = c.readlines()
    c.close()
    number = 1
    numbered_list_of_lines = []
    for i in list_of_lines:
        numbered_lines = "{0:0>4}".format(number) + " " + i
        numbered_list_of_lines.append(numbered_lines)
        number += 1
    f = open("numerated_text.txt", "w")
    for i in numbered_list_of_lines:
        f.write(i)
    f.close()

Post a Comment for "Adding Line Numbers To A File"