-3

Im trying to read lines from a text file and print the number of the line and the line next to the number

Ive tried using enumerate but I want to find another way of doing it

the file contains :

pizza
hello
goodbye

I want to print to the screen

1-pizza
2-hello
3-goodbye
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 4
    You should show what you've tried. – Sayse Apr 21 '19 at 18:55
  • 2
    `enumerate` is the cleanest way to do it. I can think of other ways, but enumerate is the simplest. – Valentino Apr 21 '19 at 18:58
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [mcve] – Patrick Artner Apr 21 '19 at 19:00
  • Duplicate: [Printing out each line (from file) with line number python](https://stackoverflow.com/questions/43197657/printing-out-each-line-from-file-with-line-number-python) – Patrick Artner Apr 21 '19 at 19:03

1 Answers1

1

a simple for loop over the file:

lineCounter=0
with open('C:/t.txt') as readObj:
    lines=readObj.readlines()
    for line in lines:
        line=line.rstrip('\n')
        lineCounter += 1
        print('{}-{}'.format(lineCounter,line))
Rebin
  • 516
  • 1
  • 6
  • 16