如何通过python更改文件系统编码?

时间:2013-11-24 06:59:30

标签: python encoding filesystems

>>> import sys
>>> sys.getfilesystemencoding()
'UTF-8'

我该如何改变?我知道如何更改默认的系统编码。

>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('ascii')

但是没有sys.setfilesystemencoding。

2 个答案:

答案 0 :(得分:7)

There are two ways to change it:

1) (linux-only) export LC_CTYPE=en_US.UTF8 before launching python:

$ LC_CTYPE=C python -c 'import sys; print(sys.getfilesystemencoding())'
ANSI_X3.4-1968
$ LC_CTYPE=C.UTF-8 python -c 'import sys; print(sys.getfilesystemencoding())'
UTF-8

Note that LANG serves as the default value for LC_CTYPE if it is not set, while LC_ALL overrides both LC_CTYPE and LANG)

2) monkeypatching:

import sys
sys.getfilesystemencoding = lambda: 'UTF-8'

Both methods let functions like os.stat accept unicode (python2.x) strings. Otherwise those functions raise an exception when they see non-ascii symbols in the filename.

答案 1 :(得分:3)

在许多情况下,文件系统编码是操作系统的固有属性。它无法更改 - 如果由于某种原因,您需要创建名称编码与文件系统编码所暗示不同的文件,请不要将Unicode字符串用于文件名。 (或者,如果您使用的是Python 3,请使用字节对象而不是字符串。)

See the documentation for details.特别要注意的是,在Windows系统上,文件系统本地 Unicode,因此实际上没有进行任何转换,因此,不可能使用替代方案文件系统编码。