在Python中写入文件时出现类型错误
我正在编写一个Python脚本,在对网页进行更改时通知我,并将网页的当前状态存储到文件中,以便在重新启动后无缝恢复。 代码如下:在Python中写入文件时出现类型错误,python,python-2.7,urllib,Python,Python 2.7,Urllib,我正在编写一个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 v
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
回溯(最近一次呼叫最后一次):
文件“April_傻瓜.py”,第20行,在
打开(文件路径,“w”)。写入(html)
TypeError:应为字符缓冲区对象
------------------
(程序已退出,代码为:1)
按return继续
我不知道这意味着什么。我对Python比较陌生。任何帮助都将不胜感激。
urllib.urlopen
不返回字符串,而是以类似文件的对象返回响应。您需要阅读该回复:
html = imported.read()
只有这样,
html
才是可以写入文件的字符串。作为旁白,使用open(filename)。read()
是,因为您从不关闭文件。写作也是如此。请尝试改用:
with
块将在您离开该块时自动关闭文件。投票给您仅仅是因为您的链接让我发现了memoryview,我非常需要它。谢谢
try:
with open(filepath,"r") as htmlfile:
html = htmlfile.read()
except:
html=""