Python无法打开日文文件名
我一直在写一个Python脚本,目的是打开一个带有Unicode名字的文件(主要是日文),然后把它保存为一个随机生成的非Unicode文件名,运行在Windows Vista 64位系统上,但我遇到了一些问题……它就是不工作。对于非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>)
2 个回答
1
我猜测,sys.argv1 和 sys.argv[2] 只是字节数组,并不支持Unicode。你可以通过打印它们来确认,看看它们是不是你期待的字符。你还应该打印一下 type(sys.argv1),以确保它们是正确的类型。
命令行参数是从哪里来的?是来自另一个程序,还是你在命令行上输入的?如果是来自另一个程序,你可以让那个程序把它们编码成UTF-8,然后让你的Python程序从UTF-8解码。
你使用的是哪个版本的Python?
补充:这里有一个稳妥的解决方案: http://code.activestate.com/recipes/572200/
3
你需要把你的 inpath
转换成unicode格式,像这样:
inpath = sys.argv[1]
inpath = inpath.decode("UTF-8")
filein = open(inpath, "rb")
我猜你是在用Python 2.6,因为在Python 3中,所有字符串默认都是unicode格式,所以这个问题就不会出现了。