Python:从脚本中打开一个名为 xls 的 unicode 文件

标签 python windows unicode subprocess os.system

如何从 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/

相关文章:

python - 当文本包含表情符号字符时,model.save() 调用时出现 Django "surrogates not allowed"错误

python - isdecimal 和 isdigit 之间的区别

python - 在 Pandas 中压平多层嵌套 JSON 并导出为 CSV

Windows 用户名最大长度

c - 在 GUI 编程中获取输入

c# - 无法生成临时类(结果=1)有什么想法吗?

c++ - OS X 上的字符串到 wstring 的转换

python - 如何使用递归来使用 Python 查找回文?

python - opencv 的 cv.GetSubRect 和 PIL 的 .crop() 有区别吗?

python - IOLoop.current().run_in_executor() 和 ThreadPoolExecutor().submit() 的区别