Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does the following python code gives unexpected results sometimes?
    primarykey
    data
    text
    <p>I wrote a small script to fetch some data from a website and store it in a file. The data is fetched in a variable "content".</p> <pre><code>try: content = urllib.urlopen(url).read() except: content = "" </code></pre> <p>The file has a few short phrases, each on a new line. I intend to simply update the last line of the file every time I run the script. And so I'm using the following code:</p> <pre><code>try: f = open("MYFILENAME","r+") # open file for reading and writing lines = f.readlines() replace_index = len(lines[-1]) f.seek(long(int(f.tell())-replace_index)) # should move to the start of last line # content[start:end] has no "\n" for sure. f.write(content[start:end] + " " + now + "\n") except Exception as exc: print "This is an exception",exc finally: f.close() </code></pre> <p>Now, I use the crontab to run this script every minute and update "MYFILENAME". But the script gives weird behavior <strong>sometimes</strong>,i.e., instead of replacing the last line, it appends a new line to the file. These <em>sometimes</em> are usually associated with me restarting the computer or re-using it after putting it on sleep. </p> <p>If original file was:</p> <pre><code>xyz abc bla bla bla 1 2 3 </code></pre> <p>I'm expecting the output to be:</p> <pre><code>xyz abc bla bla bla my_new_small_phrase </code></pre> <p>Instead, sometimes I get:</p> <pre><code>xyz abc bla bla bla 1 2 3 my_new_small_phrase </code></pre> <p>What is wrong with the above code? (I'm using both <em>crontabs</em> and <em>seek and tell</em> functions for the first time, so I'm not sure about either of them.) Or is it something to do with the <strong>"\n"</strong> at the end of write() function?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload