码迷,mamicode.com
首页 > 编程语言 > 详细

Python中中文路径处理问题的研究

时间:2014-07-15 12:50:18      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:python   编码   中文   路径   utf-8   

a = ‘你‘ 为 str 对象
a = u‘你‘ 为 unicode 对象


1.

>>> print ‘u‘  + ‘你‘
>>> u浣
输出乱码


2.

>>> print ‘u‘  + u‘你‘
>>> u你
正常


3.

>>> print ‘u你‘
>>> u浣

输出乱码


4.
>>> print ‘u你‘ + ‘u‘
>>> u浣爑
输出乱码


5.

>>> print u‘u你‘ + ‘u‘
>>> u你u
正常


6.

>>> print u‘u你‘ + ‘你‘
出现错误 UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0xe4 in position 0: ordinal not in range(128)
分析:‘你‘在内存中 为 0xe4,而python默认的编码方案是ascii,ascii无法识别0xe4


7.

>>> print u‘u你‘ + u‘你‘
>>> u你你
正常

8.
>>> print ‘u你‘ + u‘你‘
出现错误 UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0xe4 in position 1: ordinal not in range(128)

9.
>>> print ‘u你‘.decode(‘utf-8‘) + u‘你‘
>>> u你你
正常

10.
而在处理由系统采集的含有中文的路径时,使用string.decode(‘utf-8‘)就不一定行了,因为简体中文的windows系统默认编码为gb2312,繁体中文版会采用Big5码
实验过程如下:
file_from = sys.argv[1] 为由系统采集的包含中文的路径
file_to = file_from[:file_from.rfind(‘\\‘)+1].decode(‘utf-8‘)  + u‘你_‘ + file_from[file_from.rfind(‘\\‘)+1:].decode(‘utf-8‘)

print file_to

将出现错误:UnicodeDecodeError: ‘utf8‘ codec can‘t decode byte 0xbb in position 24: invalid start byte

应该使用:decode(‘gb2312‘)
file_to = file_from[:file_from.rfind(‘\\‘)+1].decode(‘gb2312‘)  + u‘你_‘ + file_from[file_from.rfind(‘\\‘)+1:].decode(‘gb2312‘) 

print file_to 正常


11.

而如果file_from是由你自己写入的包含中文的路径,如file_from = ‘c:\你.txt’

那么就应该用decode(‘utf-8‘)

可以参考上面的第7点和第9点


不足及错误之处,请批评指正!!谢谢!!


参考文章:

Why you benefit from using UTF-8 Unicode everywhere in your web applications


Python中中文路径处理问题的研究,布布扣,bubuko.com

Python中中文路径处理问题的研究

标签:python   编码   中文   路径   utf-8   

原文地址:http://blog.csdn.net/thoughts_storms/article/details/37777733

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!