FunnyFunkyBuggy
FunnyFunkyBuggy

Reputation: 613

writing counter with python

I am writing a counter for my webpage using python. And my code is as follow:

#!/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>
""" 

When I opened the webpage, only half of the page can be shown. Then I opened the source code of the page, only the following code was shown:

<html>
<center>
<p>The webpage has been accessed for</p>

After that, I tried another version:

#!/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()

It works better but not what I expected:

<html>
<center>
<p>The webpage has been accessed for</p>
<p>40</p>
<p>times</p>
</center>
</html>

The code is ok but I found that the counter can't update itself! What can I do about it?

Upvotes: 0

Views: 2008

Answers (1)

MikeTGW
MikeTGW

Reputation: 393

Your coding is working fine as is. As others pointed out in the comments, you might want to check your file permissions.

I rewrote your code a little bit, its generally better to use the with functionality in Python for handling file objects. I also used string formatting to make your print statements a little neater / easier to read:

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)

Upvotes: 1

Related Questions