html - python 读写文件的编码问题
ringa_lee
ringa_lee 2017-04-18 09:45:57
[Python讨论组]

代码如下:

#-*-coding:utf-8-*-
import os
import re
def getMainModel():
    mainfilename = os.getcwd() + "\mainmodel.html"
    mainmodel = ""
    try:
        mainfile = open(mainfilename, 'r')
    except:
        err = "

打开主模板文件时出现错误

" return err for line in mainfile.readlines(): mainmodel += line return mainmodel def getResult(): resfilename = os.getcwd() + "\\res.html" res = "" try: resfile = open(resfilename, 'r') except: err = "

打开结果文件时出现错误。

" return err for line in resfile.readlines(): res += line return res #print res def getNeed(res): patt_style = r'' patt_body = r"

.*

 

" ps = re.compile(patt_style, re.DOTALL) pb = re.compile(patt_body, re.DOTALL) style = re.search(ps, res) body = re.search(pb, res) #print style.group() #print #print body.group() return (style.group(), body.group()) def combine(main_model, res_style, res_body): html_position = main_model.index('') mail = main_model[:html_position + 7] + res_style mail += '\n' mail += main_model[html_position + 7:] mail += res_body mailfile = open('resmail.html', 'w') mailfile.write(mail) mailfile.close() if __name__ == "__main__": main_model = getMainModel() res = getResult() res_style, res_body = getNeed(res) combine(main_model, res_style, res_body)

我写这段代码想把两个html文件合并起来
mainmodel.html文件是这样的:

res.html文件是这样的:

运行后的效果是这样的:

代码运行完以后,效果是这样的,出现的中文都变成了乱码,我试了打开时encode,但是在combine函数里index的时候就会找不到标签。正确的做法应该是什么?

啊,忘了说了,用的是python2.x.

问题已解决,谢谢。

ringa_lee
ringa_lee

ringa_lee

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号