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

本文详细解析了Python中Unicode编码的应用与处理方法,包括字符串拼接、路径处理及不同编码下的问题解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值