为什么下面的python代码有时会给出意外的结果?

2024-09-29 06:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个小脚本,从一个网站获取一些数据并将其存储在一个文件中。数据是在变量“content”中获取的。你知道吗

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

文件中有几个简短的短语,每一个都在新行中。我只想在每次运行脚本时更新文件的最后一行。所以我使用以下代码:

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

现在,我使用crontab每分钟运行一次这个脚本并更新“MYFILENAME”。 但是脚本有时会出现奇怪的行为,即,它不会替换最后一行,而是在文件中附加一个新行。这些问题有时与我重启电脑或在电脑进入睡眠状态后重新使用电脑有关。你知道吗

如果原始文件是:

xyz
abc
bla bla bla
1 2 3

我希望输出是:

xyz
abc
bla bla bla
my_new_small_phrase

相反,有时我会:

xyz
abc
bla bla bla
1 2 3
my_new_small_phrase

上面的代码有什么问题?(我第一次使用了crontabseek and tell函数,所以我不确定这两个函数是什么。) 还是与write()函数末尾的“\n”有关?你知道吗


Tags: 文件数据函数代码脚本opencontentstart