我正在使用python为我的网页编写一个计数器。我的代码如下:
#!/usr/bin/python
print """#Content-type: text/html\r\n\r\n
<html>
<center>
<p>The webpage has been accessed for</p>"""
f=open( "number.txt", "r" )
count = f.read()
n = int( count )
f.close()
f=open( "number.txt", "w" )
f.write( str(n+1) )
f.close()
print "<p>"+count+"</p>"
print """<p>times</p>
</center>
</html>
"""
当我打开网页时,只能显示一半页面。然后我打开了页面的源代码,只显示了以下代码:
<html>
<center>
<p>The webpage has been accessed for</p>
之后,我尝试了另一个版本:
#!/usr/bin/python
print """#Content-type: text/html\r\n\r\n
<html>
<center>
<p>The webpage has been accessed for</p>"""
f=open( "number.txt", "r" )
count = f.read()
n = int( count )
print "<p>"+count+"</p>"
print """<p>times</p>
</center>
</html>
"""
f.close()
f=open( "number.txt", "w" )
f.write( str(n+1) )
f.close()
它效果更好,但不是我的预期:
<html>
<center>
<p>The webpage has been accessed for</p>
<p>40</p>
<p>times</p>
</center>
</html>
代码还可以,但我发现计数器无法更新! 我该怎么办呢?
答案 0 :(得分:1)
您的编码工作正常。正如其他人在评论中指出的那样,您可能需要检查文件权限。
我稍微重写了一下你的代码,它在Python中通常是better to use the with
functionality来处理文件对象。我还使用string formatting使您的打印语句更整洁/更容易阅读:
with open( "count.txt", "r" ) as f:
count = f.read()
output = """#Content-type: text/html\r\n\r\n
<html>
<center>
<p>The webpage has been accessed for</p>
<p>{count}</p>
<p>times</p>
</center>
</html>
""".format(count=count)
count = int(count)
with open( "count.txt", "w" ) as f:
f.write( str(count+1) )
print(output)