Python write()写不进去

如图,往一个html文件里写<a>标签,带变量的字符串写不进去,在write('<a></a>')可以写进去,不知为什么

我用的2.7 是可以写入的,楼主把异常打印出来看看具体是什么异常

追问

title是从网站里爬下来的汉字,应该是编码的问题
错误提示:
'ascii' codec can't encode characters in position 77-97: ordinal not in range(128)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-10-07

这边测试没有问题,最好发一下完整的程序。下面是测试的代码


class htm:
    def addHtmlNode(self, title, href):
        fout = open('list.htm', 'a+')
        node = "<br/><a href='%s'>%s</a>" % (href, title)
        print(node)
        try:
            fout.write(node)
            fout.flush()
        except:
            print("error")
        print("3")
        fout.close()
        print("4")
h = htm()
h.addHtmlNode('hello', 'url')

追问

title是从网站里爬下来的汉字,应该是编码的问题
错误提示:
'ascii' codec can't encode characters in position 77-97: ordinal not in range(128)

追答

Python在处理多语言方面确实有些问题,几个建议
1、open语句指定文件的编码encoding
open(file,
mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True,
opener=None)
2、另存源代码文件,选择合适的编码
3、爬下来的汉字保存成字节,回避Python的编码处理问题

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网