0

I am writing this code to read a text file and then print the line number after each line here is my code

with open("newfile.txt") as f:
 for line in f:
  x=1
  y=str(x)
  print(line)
  print(x)
  x=x+1
f.close()

I should expect some thing like that

Line one

1

Line two

2

Line three

3

but instead I am getting

Line one

1

Line two

1

Line three

1

Why is that !?

1
  • 2
    x is initiated again in every loop. So if you want to do it like this, you have to define it outside the loop and only increment in the loop. Commented Aug 20, 2015 at 12:29

4 Answers 4

3

You can just use enumerate() :

with open("newfile.txt") as f:
 for num,line in enumerate(f,1):
      print line,'\n',num

Also note that you don't need to close the file when you use the with statement. It will automatically does it for you.

And about the x variable in your code, you shouldn't initialized it in your loop, you need to put x=1 out of the loop.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that solved my problem ,However I don't understand why the integer x is not incrementing in the for loop?
you assign x=1 at the beginning of every run of the loop. you should do that before the for loop. more elegant; for i, line in enumerate(f):.
Yes that was obvious ! how i didn't see it ,Sorry my fault
1

Adding comments to your code will help you see why you always print out 1.

with open("newfile.txt") as f:
  for line in f:
   x=1            # x is now equal to 1
   y=str(x)       # x is still 1, y is now equal to '1'
   print(line)    # prints out the line
   print(x)       # 1 is printed
   x=x+1          # you now add 1 to x, but don't do anything with this 
                  # updated value, because in the next loop x is again
                  # initialised to 1
 f.close()

Comments

1

The problem is that you are initializing x to 1 inside the loop and before the print statement.

try:

x = 1
with open("newfile.txt") as f:    
  for line in f:
    y = str(x)
    print(line)
    print(x)
    x += 1 

Comments

0

The issue with the code would be the x=1 inside of the loop. By moving that outside and initializing that before you should get the result you want. For example:

 x=1
 with open("newfile.txt") as f:
 for line in f:
 y=str(x)
 print(line)
 print(x)
 x=x+1

This should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.