2013-03-31 85 views
0

我写一个Python脚本来通知我什么时候更改了网页制作和网页的当前状态保存到一个文件到文件,以便在重新启动后恢复的无缝连接。 的代码如下:错误类型Python写

import urllib 
url="http://example.com" 
filepath="/path/to/file.txt" 
try: 
    html=open(filepath,"r").read() # Restores imported code from previous session 
except: 
    html="" # Blanks variable on first run of the script 
while True: 
    imported=urllib.urlopen(url) 
    if imported!=html: 
    # Alert me 
    html=imported 
    open(filepath,"w").write(html) 
# Time delay before next iteration 

运行脚本返回:

Traceback (most recent call last): 
    File "April_Fools.py", line 20, in <module> 
    open(filepath,"w").write(html) 
TypeError: expected a character buffer object 

------------------ 
(program exited with code: 1) 
Press return to continue 

我不知道这意味着什么。我对Python比较陌生。任何帮助将非常感激。

回答

1

urllib.urlopen没有返回一个字符串,它返回一个类文件对象的响应。您需要阅读该响应:

html = imported.read() 

只有然后html你可以写一个文件的字符串。

+0

谢谢!这都是现在:) – user118990

1

顺便说一句,使用open(filename).read()not considered good style,因为你永远不关闭文件。写作也是一样。尝试使用context manager代替:当你离开块

try: 
    with open(filepath,"r") as htmlfile: 
     html = htmlfile.read() 
except: 
    html="" 

with块将自动关闭文件。

+0

工作upvoting你只是因为你的链接让我发现memoryview,这是我需要的不好。谢谢! – bobrobbob