1

I have a file that has the following contents:

a  
b  
c  
d

I'm reading this in Python using the following code:

f = open('foo.txt')
w = f.readline()

while w is not '' :
  print w
  w = f.readline()

According to the docs

if f.readline() returns an empty string, the end of the file has been reached

Why then do I go into an infinite loop?

6
  • 1
    I figured out the issue. Changing the while condition to w != '' makes it work fine. I'd still like to know why is not causes an infinite loop. Commented Feb 28, 2013 at 4:10
  • I don't go into an infinite loop with that code. Commented Feb 28, 2013 at 4:10
  • Eric, that's interesting. I go into an infinite loop running on Ubuntu 12.10 / 12.04, Python 2.7.3. I tried this on two different systems, and was able to reproduce the issue. Commented Feb 28, 2013 at 4:11
  • I think @FatalError's answer is correct; I'm on Windows 7 (Py 2.7). Perhaps some optimization is making them into the same object. Commented Feb 28, 2013 at 4:12
  • Don't write while w is not '' :, just write while w: Commented Feb 28, 2013 at 4:21

4 Answers 4

5

The is operator tests if two references reference exactly the same object. In this case, you want an equality check as you noted.

The infinite loop happened because although it returned '', it was a different instance of str. Different instance, but same value.

Python may or may not choose as an optimization to resuse an existing str object (they are immutable, after all). You should not depend on this type of behavior in general, however, unless the documentation specifically mentions otherwise (like for None as it's the one and only instance of NoneType).

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

Comments

1

This is interesting.

If you replace

while w is ''

with

while w != ''

the code would run successfully.

This means that readline() returns a new instance of the empty string, instead of returning the global one which you get when you execute

s = ''
t = ''
assert s is t

Comments

1

Try this

f = open('foo.txt')

while 1:
    line = f.readline()
    if not line:
        break
    print line

Comments

1
with open('workfile', 'r') as f:
  read_data = f.read()
f.closed

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.

Refer to this link: http://docs.python.org/2/tutorial/inputoutput.html

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.