简体   繁体   中英

Why does the following python code gives unexpected results sometimes?

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".

try:
    content = urllib.urlopen(url).read()
except:
    content = ""

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:

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()

Now, I use the crontab to run this script every minute and update "MYFILENAME". But the script gives weird behavior sometimes ,ie, instead of replacing the last line, it appends a new line to the file. These sometimes are usually associated with me restarting the computer or re-using it after putting it on sleep.

If original file was:

xyz
abc
bla bla bla
1 2 3

I'm expecting the output to be:

xyz
abc
bla bla bla
my_new_small_phrase

Instead, sometimes I get:

xyz
abc
bla bla bla
1 2 3
my_new_small_phrase

What is wrong with the above code? (I'm using both crontabs and seek and tell functions for the first time, so I'm not sure about either of them.) Or is it something to do with the "\\n" at the end of write() function?

you could also do it like this:

lines = open("filename", "r").readlines()
del lines[-1]

f = open("filename", "w")
for line in lines:
 f.write(line)

f.write("new content")
f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM