下载的文件名是乱码

本文介绍了在Ubuntu环境下使用Python解决文件路径乱码问题的方法,包括使用urllib库的unquote函数进行解码,并提供了实例代码演示。

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

环境:ubuntu,python

下载了文件,有一些是乱码,例:

%5Byyman%5D%5BYama%20no%20Susume%20Second%20Season%5D%5B19%5D%5B1280x720%5D%5B%E7%AE%80%E4%BD%93%5D%5BMP4%5D.mp4

百度,查到了资料:

http://www.crifan.com/python_urllib_unquote_messy_issue/

解决办法:

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> s='%5Byyman%5D%5BYama%20no%20Susume%20Second%20Season%5D%5B19%5D%5B1280x720%5D%5B%E7%AE%80%E4%BD%93%5D%5BMP4%5D.mp4'
>>> print urllib.unquote(s)
[yyman][Yama no Susume Second Season][19][1280x720][简体][MP4].mp4


注释:原文用‘print urllib.unquote(str(s)).decode('utf8')’处理,我的也可以。

对于原文中的例子测试:

>>> s = u'\u957f\u6625\u5e02'
>>> print urllib.unquote(str(s)).decode('utf8')Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
>>> print s
长春市


如上所示,我这里处理按原文不行。不过对于原文第一个例子倒是可以,但是我的方法也是可以的:

>>> s="%E9%98%BF%E6%9D%B0%E5%A7%90%E5%A6%B9%E7%BB%A7%E7%BB%AD%E6%B3%AA%E6%B5%81%E6%BB%A1%E9%9D%A2%E2%80%A6%E2%80%A6%28%2A%5E__%5E%2A%29%26nbsp%3B%E8%BF%99%E7%A7%8D%E8%A1%A8%E8%BE%BE%E5%A5%BD%E5%96%9C%E5%89%A7%E5%93%A6%EF%BC%81%E4%BA%8C%E5%85%AC%E4%B8%BB%E5%A4%A7%E4%BA%BA%E6%88%90%E7%BB%A9%E4%B8%8D%E9%94%99%E5%93%A6%EF%BC%81%E4%B9%88%E4%B9%88%E5%93%92%3Cimg%20src%3D%22http%3A%2F%2Fwww.sinaimg.cn%2Fuc%2Fmyshow%2Fblog%2Fmisc%2Fgif%2FE___0088EN00SIGT.gif%22%20style%3D%22margin%3A1px%3Bcursor%3Apointer%3B%22%20onclick%3D%22window.open%28%27http%3A%2F%2Fblog.sina.com.cn%2Fmyshow2010%27%29%22%20border%3D%220%22%20title%3D%22%E9%A1%B6%22%20%2F%3E"
>>> print urllib.unquote(str(s)).decode('utf8')阿杰姐妹继续泪流满面……(*^__^*)&nbsp;这种表达好喜剧哦!二公主大人成绩不错哦!么么哒<img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0088EN00SIGT.gif" style="margin:1px;cursor:pointer;" οnclick="window.open('http://blog.sina.com.cn/myshow2010')" border="0" title="顶" />
>>> print urllib.unquote(s)
阿杰姐妹继续泪流满面……(*^__^*)&nbsp;这种表达好喜剧哦!二公主大人成绩不错哦!么么哒<img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0088EN00SIGT.gif" style="margin:1px;cursor:pointer;" οnclick="window.open('http://blog.sina.com.cn/myshow2010')" border="0" title="顶" />


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值