最近遇到一个弄不太懂的问题, 是关于用 Python 遍历文件夹的文件并把文件名存储起来,对于一些有特殊字符的文件名出现了一些比较奇怪的问题
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import sys
reload(sys)
sys.setdefaultencoding('utf8')
p(sys.getdefaultencoding)
s = '中文ì'
print s#输出"中文ì"
print json.dumps({'name':'ìì'})#奇葩的输出:{"name": "i\u0300\u00ec"}
print json.dumps({'name2':'Elpìs--Aletheia\'s lullaby.mp3'})#特殊字符是从上名的输出 s 语句中的结果中copy过来的,输出是正确的
print json.dumps({'name4':'Elpìs - Lost in Thoughts'})#直接从文件名中拷贝来的,特殊字符输出是错误的编码
对于特殊字符 'ì' 的编码感到迷惑,正确的输出应该为'\u00ec', '中文ì'中的特殊字符是文件名中copy过来的,这种格式的时输出 'i\u0300' 这么奇怪的编码出来,如何才能在获取文件名的时候就处理或者避免这种情况的发生?
运行环境:
Python 2.7.6 (default, Sep 9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information.