Python不能打开日文文件名

我一直在努力的python脚本来打开一个unicode名称(主要是日语)的文件,并保存到Windows Vista 64位随机生成(非Unicode)文件名,我有问题…它只是不工作,它工作正常非Unicode文件名(即使它有Unicode码内容),但第二个尝试传递一个Unicode文件名 – 它不起作用。
代码如下:

try: import sys, os inpath = sys.argv[1] outpath = sys.argv[2] filein = open(inpath, "rb") contents = filein.read() fileSave = open(outpath, "wb") fileSave.write(contents) fileSave.close() testfile = open(outpath + '.test', 'wb') testfile.write(inpath) testfile.close() except: errlog = open('G:\\log.txt', 'w') errlog.write(str(sys.exc_info())) errlog.close() 

而错误:

 (<type 'exceptions.IOError'>, IOError(2, 'No such file or directory'), <traceback object at 0x01092A30>) 

您必须将您的inpath转换为unicode,如下所示:

 inpath = sys.argv[1] inpath = inpath.decode("UTF-8") filein = open(inpath, "rb") 

我猜你正在使用Python 2.6,因为在Python 3中,默认情况下所有字符串都是unicode,所以这个问题不会发生。

我的猜测是,sys.argv 1和sys.argv [2]只是字节数组,不支持本地Unicode。 你可以通过打印确认,看看他们是否是你期望的角色。 你也应该打印类型(sys.argv 1 ),以确保它们是正确的类型。

命令行参数从哪里来? 他们是来自另一个程序,还是你在命令行输入? 如果他们来自另一个程序,你可以让其他程序将它们编码为UTF-8,然后让你的Python程序从UTF-8中解码它们。

你正在使用哪个版本的Python?

编辑:这是一个强大的解决方案: http : //code.activestate.com/recipes/572200/