python - 读取带有特殊字符的文件并将它们写入 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 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"...")
- 为什么
io.open
:将 Python 3 open(encoding="utf-8") 反向移植到 Python 2- 为什么应该尽可能使用
with
关键字:https ://www.pythonforbeginners.com/files/with-statement-in-python
推荐阅读
- omnet++ - OMNET++:如何在 INET 4.0 的离散 NxN 空间中移动节点?
- php - 在 codeigniter 中逃避了足够的 sql 注入保护
- r - 生成矩阵,其中每个新列是前一列的倍数
- c++ - 一对 C++ 交换方法的优点是什么?
- javascript - 动态增加字体大小
- string - 如何在 F# 中使用 String.iter
- javascript - 使用 Image URI 将照片上传到 Firebase 存储
- javascript - 数据触发器与 fancybox 冲突
- php - 提供的参数之一不可接受使用 Microsoft Graph API 创建文件夹
- php - PHP在csv的每个值的两端添加引号