-2
votes

For example, if the input file is:

def main():
    for i in range(10):
        print("I love Python")
    print("Good bye!")

Then the output would be:

1   def main():
2       for i in range(10):
3           print("I love Python")
4       print("Good bye!")

I have difficulty in adding lines to each line. My program is:

filename = input("Please enter a file name: ")
count = 0

openfile = open(filename, "r")

for lines in openfile:
    linenumbers = openfile.write(str(count)+'\t'+lines)
    count += 1

print(count)
3
I have seen that homework just a few minutes ago from a class mate. He was a bit more studious than you. Please try harder. - qwerty_so
The same exact question, interesting ...stackoverflow.com/questions/29267986/… - Daniel
@MalikBrahimi It was like a deja vu - Daniel

3 Answers

3
votes

Use a with statement to close the file buffer and just concatenate strings:

with open('file.txt', 'r') as program:
    data = program.readlines()

with open('file.txt', 'w') as program:
    for (number, line) in enumerate(data):
        program.write('%d  %s' % (number + 1, line))
3
votes

You should add:

newFile = open(yourfile, 'w')
count = 1

for line in readfile:
    newFile.write (str(count) + '\t' + line)
    count += 1
newFile.close()

If you just want to print to console write (this is according to the variable names you've used in your second edit):

for lines in openfile:
    print str(count) + '\t' + lines
    count += 1

You should do your homework yourself, though!

0
votes

I would write so:

with open(path) as src:
    for index, line in enumerate(src.readlines(), start=1):
        print '{:4d}: {}'.format(index, line.rstrip())

or

with open(path) as src:
    print '\n'.join(['{:4d}: {}'.format(i, x.rstrip()) for i, x in enumerate(src.readlines(), start=1)])