ChrisArmstrong
ChrisArmstrong

Reputation: 2521

Stuck in while loop when writing to file

My code is:

f=file('python3.mp3','wb')
conn=urllib2.urlopen(stream_url)
while True:
    f.write(conn.read(1024))

where stream_url is the url of a stream I'm saving to disk in mp3 format (python3.mp3).

The file successfully saves, but the while loop never terminates. I guess I'm a bit confused as to what the 'True' condition represents? Is it while the stream is playing? While the connection is open? I've tried adding conn.close() and f.close() within the while loop, but that throws errors because it seems like it's interrupting the writing process.

Upvotes: 0

Views: 292

Answers (2)

RichieHindle
RichieHindle

Reputation: 281505

while True loops forever, or until you break. You need to break when you've read the whole stream, something like this:

f = file('python3.mp3','wb')
conn = urllib2.urlopen(stream_url)
while True:
    packet = conn.read(1024)
    if not packet:
        break  # We've read the whole thing
    f.write(packet)

Upvotes: 1

Jashaszun
Jashaszun

Reputation: 9270

A while loop runs the code in its body for as long as its condition is True. Your condition is always True, so your while loop never ends, and rightly so. The while loop does not care about anything besides its condition.

Upvotes: 0

Related Questions