2013-03-31 4 views
0

재부팅 후 원활하게 재개하기 위해 웹 페이지가 변경되었을 때 알려주고 파일의 현재 상태를 파일에 저장하는 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

관련 문제