2
infile = open("inputex1.txt","r")
line = infile.readline()
print("1 "+line, end="")
i = 2
while line !="" :
     line = infile.readline()
     print(str(i)+" "+line, end="")
     i+=1
infile.close()

the text file is:

Mary had a little lamb,
whose fleece was white as snow.
And everyWhere that Mary went,
The Lamb was sure to go

And yet the output is:

1 Mary had a little lamb,
2 whose fleece was white as snow.
3 And everyWhere that Mary went,
4 The Lamb was sur to go
5 

my question is, why does it keep entering the while loop after reaching the fifth line? why is there a 5 in the end?

  • 2
    Because you read one more line after the last line, which will result in an empty string. Or put differently, because you check if the line is empty *after* printing it. – mkrieger1 Nov 09 '20 at 11:10
  • Does this answer your question? [How should I read a file line-by-line in Python?](https://stackoverflow.com/questions/11555468/how-should-i-read-a-file-line-by-line-in-python) – mkrieger1 Nov 09 '20 at 11:13
  • mkrieger identified the problem with your code, but note, you shouldn't be use this approach to iterate over a file line-by-line to begin with, **file objects are iterators over lines** you can iterate over them directly: `for line in infile: ...` Basically, `readline` and `readlines` are relics from very old versions of Python. I've used them exactly zero times in four years programming Python in a professional setting. You can just use `next(infile)` and `list(infile)` respectively. And usually, you just loop over the file object directly to do some line-by-line processing – juanpa.arrivillaga Nov 09 '20 at 11:26

2 Answers2

1

infile.readline() will answer an empty string when the file is read entirely.

So when you do print(str(i) + " " + line, end=""), it will print 5 .

You should just do this:

i = 2
while line !="" :
     line = infile.readline()
     if line:
         print(str(i)+" "+line, end="")
         i+=1

But you could also simplify it that way:

for i, line in enumerate(infile, 1):
    print(str(i) + " " + line, end="")

Or if you have python 3.6+:

for i, line in enumerate(infile, 1):
    print(f"{i} {line}", end="")

Also see Wasif Hasan’s answer about the with usage.

quamrana
  • 37,849
  • 12
  • 53
  • 71
Cyrille Pontvieux
  • 2,356
  • 1
  • 21
  • 29
-1

While reading from the files, they can have leading/trailing newlines, so you can use a with in best way like this:

i = 1
with open("inputex1.txt","r") as f:
  for line in f:
      print(i,line)
      i += 1

I read a python file using it, the output:

1 entries = [{'First Name': 'Sher', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '2989484'},

2            {'First Name': 'Ali', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '398439'},

3            {'First Name': 'Talha', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '3343434'},

4            {'First Name': 'Talha', 'Last Name': 'Jones', 'Age': '22', 'Telephone': '3343434'}]    

5 search = input("type your search: ")

6 found = False

7 print(search)

8 for person in entries:

9   if person["Last Name"] == search:

10     found = True

11     print("Here are the records found for your search")

12     for e in person:

13       print(e, ":", person[e])

14 

15 if not found:

16   print("There is no record found as you search Keyword")
Wasif
  • 14,755
  • 3
  • 14
  • 34