首页 > 解决方案 > 读取带有特殊字符的文件并将它们写入 html

问题描述

我有一个 python 脚本,它读取 pdf 文件的名称并将它们写入带有 PDF 链接的 HTML 文件。除非名称具有特殊字符,否则一切正常。

我在 SE 上阅读了许多其他答案,但无济于事。

f = open("jobs/index.html", "w")
#html divs go here
for root, dirs, files in os.walk('jobs/'):
    files.sort()
    for name in files:
        if ((name!="index.html")&(name!=".htaccess")):
            f.write("<a href='"+name+"'>"+name.rstrip(".pdf")+"</a>\n<br><br>\n")
            print name.rstrip(".pdf")

返回:
Caba�n-Sanchez, Jane.pdf
Smith, John.pdf

这当然会破坏文本和该 pdf 的链接。

如何正确编码文件或“名称”变量,以便正确写入特殊字符?
即,Cabán-Sanchez,Jane.pdf

标签: python

解决方案


我不习惯 python 2.7,但这应该可以:

from io import open

with open("jobs/index.html", "w", encoding='utf-8') as f:
    for root, dirs, files in os.walk('jobs/'):
        files.sort()
        for name in files:
            if not name in ("index.html", ".htaccess"):
                f.write("<a href='{}'>{}</a>\n<br><br>\n".format(name, name.rstrip(".pdf")))
                print name.rstrip(".pdf")

您还应该通过在模块顶部添加以下行来在 python 级别声明您的编码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

最后,您可以尝试通过添加一行来将您的字符串显式声明为 unicode u""f.write例如:

f.write(u"...")

推荐阅读