Python - html2text写入文件

时间:2015-02-19 09:35:39

标签: python

我有包含html标签的文本文件,我想用Python使用html2text删除它:

import html2text
html = open("textFileWithHtml.txt").read()
print html2text.html2text(html)

我的问题是如何将输出写入.txt文件? (我想创建没有html元素的新文本​​文件 - 该文件以前不存在)

2 个答案:

答案 0 :(得分:3)

您应该打开一个文件并写入它。

import html2text

# Open your file
with open("textFileWithHtml.txt", 'r') as f_html:
    html = f_html.read()

# Open a file and write to it
with open('your_file.txt', 'w') as f:
    f.write(html2text.html2text(html).encode('utf-8'))
  

最好在处理文件对象时使用with关键字。

它也更加pythonic 查看有关读/写文件的文件的更多信息:https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files


修改

如果您遇到编码问题,请尝试使用.encode('utf-8')。我已将其添加到我的代码剪辑中。如果您对此问题(https://docs.python.org/2/howto/unicode.html

有疑问,请查找python unicode

答案 1 :(得分:2)

您需要打开另一个文件进行写作。

import html2text
html = open("textFileWithHtml.txt")
f = html.read()
w = open("out.txt", "w")
w.write(html2text.html2text(f).encode('utf-8'))
html.close()
w.close()