Python3如何将文本文件内容原样保存为HTML文件
问题原因
你写入HTML文件的内容本身是保留了换行的,用纯文本编辑器打开RESULT.html就能看到和原TXT完全一致的格式。你在浏览器里看到换行消失,是因为HTML的默认渲染规则会忽略换行符、合并连续的空白字符(空格、制表符等),和写入操作本身无关。
解决方案
方案1:使用<pre>预格式化标签(最推荐)
HTML的<pre>标签专门用于展示预格式化文本,会完全保留文本内的所有换行、空格、制表符,和原始格式完全一致。你只需要在写入TXT内容前后分别加上<pre>的开标签和闭标签即可:
with open('TEST.txt', 'r') as firstfile, open('RESULT.html', 'w') as secondfile: # 写入pre开标签 secondfile.write('<pre>') # 写入原TXT所有内容 for line in firstfile: secondfile.write(line) # 写入pre闭标签 secondfile.write('</pre>')
如果你的TXT内容里包含<、>、&等HTML特殊字符,需要先转义再写入,避免被浏览器解析为HTML标签,修改后代码如下:
import html with open('TEST.txt', 'r') as firstfile, open('RESULT.html', 'w') as secondfile: secondfile.write('<pre>') for line in firstfile: # 转义HTML特殊字符,保证100%原样显示 secondfile.write(html.escape(line)) secondfile.write('</pre>')
方案2:使用CSS控制空白字符规则
你也可以给包裹文本的HTML元素添加white-space: pre的CSS样式,效果和<pre>标签完全一致:
with open('TEST.txt', 'r') as firstfile, open('RESULT.html', 'w') as secondfile: # 写入带样式的div开标签 secondfile.write('<div style="white-space: pre;">') for line in firstfile: secondfile.write(html.escape(line)) secondfile.write('</div>')
注意事项
你原代码中使用追加模式a打开HTML文件,如果目标文件已经存在,新内容会追加到原有内容末尾。如果需要每次生成全新的HTML文件,建议改为写入模式w打开文件。
内容的提问来源于stack exchange,提问作者Darik
相关产品推荐
相关产品推荐

