Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my script write to a file?

import time
import traceback
import sys
import tools
from BeautifulSoup import BeautifulSoup

f = open("randomwords.txt","w")
while 1:
    try:
        page = tools.download("http://wordnik.com/random")
        soup = BeautifulSoup(page)
        si = soup.find("h1")
        w = si.string
        print w
        f.write(w)
        f.write("\n")
        time.sleep(3)
    except:
        traceback.print_exc()
        continue


f.close()

It prints just fine. It just won't write to the file. It's 0 bytes.

like image 446
TIMEX Avatar asked Mar 21 '26 04:03

TIMEX


1 Answers

You can never leave the while loop, hence the f.close() call will never be called and the stream buffer to the file will never be flushed.

Let me explain a little bit further, in your exception catch statement you've included continue so there's no "exit" to the loop condition. Perhaps you should add some sort of indicator that you've reached the end of the page instead of a static 1. Then you'd see the close call and information printed to the file.

like image 85
wheaties Avatar answered Mar 22 '26 18:03

wheaties



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!