Python的file.read()方法無法讀全文件


作為一個python的菜鳥,最近在用python讀取html文件內容。

image

由於文件本身存在亂碼(應該是保存到本地產生的),所以使用以下代碼讀取時,讀取到亂碼處就無法返回了。

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

歡迎各位大牛指導。

 

來自:http://www.cnblogs.com/anic/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM