1
demoFile=open("lambpoem.txt","r")
for i in demoFile:
    print(i)

how do I modify the code in order for it to include the line number before the text in that line?

  • 1
    Function "enumerate" can be helpful here. – Michael Butscher Feb 23 '20 at 17:37
  • What is the issue, exactly? Have you tried anything, done any research? Stack Overflow is not a free code writing service. See: [tour], [ask], [help/on-topic], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users. – AMC Feb 23 '20 at 18:35
  • Not only is the question subpar, the accepted answer is less than ideal. – AMC Feb 23 '20 at 18:35
  • Does this answer your question? [Get Line Number of certain phrase in file Python](https://stackoverflow.com/questions/3961265/get-line-number-of-certain-phrase-in-file-python) – AMC Feb 23 '20 at 18:36

2 Answers2

3

Here is an example with enumerate

with open('lambpoem.txt') as f:
    for line in enumerate(f):
        print(f'{line[0] + 1}. {line[1]}')
0

The way that I do this but this is certainly not the only way would to do so.

with open('File.txt', 'r') as f:
    files = f.readlines()
for i in range(len(files)):
    print(i, files[i])
Ben
  • 452
  • 4
  • 9
  • 1) Why name a variable holds a list of lines `files` ? 2) The `mode='r'` parameter to `open()` is unnecessary. 3) Why not use `enumerate()` ? – AMC Feb 23 '20 at 18:38
  • @AMC 1) To make it look simpler for a new coder 2) I find it makes my code look clearer and doesn't effect speed 3) Same as the reason for 1 – Ben Feb 23 '20 at 18:41