获取当前运行脚本的unicode路径

时间:2016-05-25 15:37:01

标签: python unicode

本网站上存在

This问题,但它存在缺陷,因为它返回<type 'str'>(使用__file__时和使用模块inspect时)而不是<type 'unicode'> {1}}我需要的路径包含非ascii字符(希伯来字符,具体而言)。

如何在文件系统编码中获取<type 'unicode'>中当前运行脚本的路径和文件名?是否有内置的Unicode友好功能用于执行此操作或任何解决方案?

仅使用__file__.encode(sys.getfilesystemencoding())调用ascii codec can't decode byte ...失败。

2 个答案:

答案 0 :(得分:2)

您需要.decode(),而不是.encode()。要从unicode转到str,一个会对进行编码。要转向另一个方向,一个解码

尝试:

import sys
filename = __file__.decode(sys.getfilesystemencoding())
print type(filename), filename

结果:

$ python 'קוֹבֶץ.py'
<type 'unicode'> קוֹבֶץ.py

答案 1 :(得分:1)

我想您要使用decode代替encode

>>> type('string'.encode('utf-8'))
<type 'str'>
>>> type('string'.decode('utf-8'))
<type 'unicode'>

一般来说,encode返回一个字节串,decode是一个unicode对象。

相关问题