如何从 Windows 下的 Python 脚本中打开一个名为 unicode 的文件(带有 空格) ?
文件名例如:Hello עולם.xls
对于非 unicode 非间隔 xls 文件,os.system(filename)
效果很好。
对于非 unicode 间隔的 xls 文件,os.system('"'+filename+'"')
效果很好。
但是对于一个 unicode 空格的 xls 文件...
os.system(filename)
和 subprocess.call(new_filename)
都给出:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 12-13: ordinal not in range(128)
os.system(new_filename.encode('UTF-8'))
给出:
'Hello' is not recognized as an internal or external command, operable program or batch file.
和 subprocess.call(new_filename.encode('UTF-8'))
给出:
WindowsError: [Error 2] The system cannot find the file specified
最佳答案
os.startfile()
如 Bradley (+1) 所述,但请确保传入 Unicode 字符串,而不是字节字符串。
Windows NT 文件名本身是 Unicode,Windows 上的 Python(与大多数其他脚本语言不同)内置了特定支持,用于将 Unicode 字符串传递到需要文件名的 API 中:
os.startfile(u'Hello \u05e2\u05d5\u05dc\u05dd.xls') # u'Hello עולם.xls'
如果您传入一个字节字符串,它将转而转到标准 C stdio
库,该库在 Microsoft C 运行时将使用机器的默认字符集(又名 ANSI)将字节字符串映射到 Unicode 文件名代码页),这是 getfilesystemencoding()
返回的内容。如果文件名中的每个字符都可以在 ANSI 代码页中表示,那仍然有效,但是示例文件名对于除了希伯来语安装的 Windows 之外的任何东西都会失败。
不幸的是,相同的 Unicode 支持不适用于 system()
或 subprocess
。但在这种情况下您可能不需要使用命令行。
关于Python:从脚本中打开一个名为 xls 的 unicode 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5522524/