How to change file system encoding via python?

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

How can I change this? I know how to change the default system encoding.

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

But there is no sys.setfilesystemencoding.

+7
python filesystems encoding
source share
2 answers

Encoding the file system in many cases is an integral property of the operating system. It cannot be changed - if for some reason you need to create files with names encoded differently than is implied in the encoding of the file system, do not use Unicode strings for file names. (Or, if you're using Python 3, use the bytes object instead of a string.)

See the documentation for more details. In particular, note that on Windows systems, the file system is Unicode source, so the conversion is not really, and therefore, it is not possible to use alternative file system encoding.

+3
source share

There are two ways to change it:

1) (Linux only) export LC_CTYPE=en_US.UTF8 before running 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 is used 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 allow functions like os.stat to accept unicode strings (python2.x). Otherwise, these functions throw an exception if characters other than ascii appear in the file name.

+5
source share

All Articles