You are looking for the enumerate
function: https://docs.python.org/2/library/functions.html#enumerate
For instance:
with open("newfile.txt", "w") as output:
for index, line in enumerate(open("myfile.txt")):
output.write("%d %s" % (index + 1, value))
1
solved How can I use python to add index numbers for the data saved in the text file [duplicate]