2

I have a .txt document with some words that are each on a different line.

For example:

hello
too
me

I am trying to figure out how to print each line with the row number that each word is on but starting at 1, not 0.

The desired output:

1 = hello
2 = too
3 = me

I already have a solution for getting the lines out of the text document:

open_file = open('something.txt', 'r')
lines = open_file.readlines()
for line in lines:
    line.strip()
    print(line)
open_file.close()

I am aware that I could print out the index that each word is at however, unless I am mistaken, that would start the row number from 0 not 1.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Pythonuser11112
  • 63
  • 1
  • 1
  • 6

1 Answers1

7

You should use enumerators and iterators rather than reading the entire file to memory:

with open('something.txt', 'r') as f:
    for i, line in enumerate(f, start=1):
        print('{} = {}'.format(i, line.strip()))
Angus
  • 3,680
  • 1
  • 12
  • 27
ssm
  • 5,277
  • 1
  • 24
  • 42
  • 2
    You can use `enumerate(f, start=1)` to avoid the addition. – Brian Rodriguez Apr 04 '17 at 03:26
  • Thanks! I had no idea. That is a good thing to know :) – ssm Apr 04 '17 at 03:26
  • As stated in [answer], please avoid answering unclear, overly-broad, typo, unreproducible, or duplicate questions. Write-my-code requests and low-effort homework questions are off-topic for [so] and more suited to professional coding/tutoring services. Good questions adhere to [ask], include a [mcve], have research effort, and have the potential to be useful to future visitors. Answering inappropriate questions harms the site by making it more difficult to navigate and encouraging further such questions, which can drive away other users who volunteer their time and expertise. – TigerhawkT3 Apr 04 '17 at 03:30
  • I didn't know about enumerate up until now, but after doing some research I can see how this solution works. Thanks! – Pythonuser11112 Apr 04 '17 at 03:48
  • 1
    you can use `print(f"{i} = {line}", end="")` to avoid the `line.strip()` – milahu Jun 12 '22 at 20:45