作為一個python的菜鳥,最近在用python讀取html文件內容。
由於文件本身存在亂碼(應該是保存到本地產生的),所以使用以下代碼讀取時,讀取到亂碼處就無法返回了。
html = open(filename).read()
查找了stackoverflow
http://stackoverflow.com/questions/7297220/cant-get-python-to-read-until-the-end-of-a-file
說在python的幫助文檔中有關於read()的說明(我沒有找到):
Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.
也就是說,即使read不傳入size的參數,有可能反回的也不是文檔的全部數據,有兩種方式解決:
方法一是使用read(size)方法
def readhtmlfile(filename): f = open(filename) html = '' while True: tmp = f.read(1024) if tmp == '': break html += tmp return html
方法二說是用readline或readlines讀取
但在我的場景,這個方法不管用:P
歡迎各位大牛指導。