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/

你可能感兴趣的:(python)