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 foll
#!/usr/bin/python
numberedfile = open("test.txt", "r")
numberedlist = numberedfile.readline()
i = 0
for lines in numberdlist:
i = i+1
print str(i) + '\t' + lines
numberdfile.close()
This prints to stdout the text pattern you describe:
with open('/etc/passwd') as fp:
for i, line in enumerate(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/python
import fileinput
import sys
for line in fileinput.input(inplace=True):
sys.stdout.write('%04d %s'%(fileinput.filelineno(), line))