[Python]编码和execfile

时间:2011-05-02 09:34:01

标签: python windows unicode encoding execfile

我正在尝试使用python 2.4执行类似的操作:

#!/usr/bin/python
# -*- coding: utf-8 -*-

afile = unicode('C:\\國立國語院.py', 'UTF-8')
execfile(afile.encode("UTF-8",'replace'))

我收到此错误:

IOError: [Errno 2] No such file or directory: 'C:\\\xef\xbb\xbf\xe5\x9c\x8b\xe7\xab\x8b\xe5\x9c\x8b\xe8\xaa\x9e\xe9\x99\xa2.py'

所以我的问题是,如果我想要exec的文件有一个带有韩文字符的名字,我该怎么办execfile?

非常感谢

2 个答案:

答案 0 :(得分:2)

我认为您应该能够在Windows上使用unicode参数进行execfile(afile),但我无法对其进行测试。

如果没有,请获取文件系统编码:

import sys
fsenc = sys.getfilesystemencoding()
execfile(afile.encode(fsenc))

答案 1 :(得分:2)

@Thomas K's answer应该可行(它适用于Linux,不适用于Python2.4上的Wine)。

execfile()可以使用exec进行模拟:

#!/usr/bin/python
# -*- coding: utf-8 -*-

exec open(ur'C:\國立國語院.py').read()