1

当尝试使用 win32file.CreateFile() 访问带有俄语 unicode 字符的文件时,我得到:

Traceback (most recent call last):
  File "test-utf8.py", line 36, in <module>
    None )
pywintypes.error: (123, 'CreateFile', 'The filename, directory name, or volume l
abel syntax is incorrect.')

这是代码。我正在使用 Python 2.7。我验证我可以使用常规 Python 'open' 打开它:

# -*- coding: UTF-8 -*-
# We need the line above to tell Python interpreter to use UTF8. 
# You must save this file with UTF8 encoding.
'''
Testing UTF8 Encoding
'''
import win32file
import os, sys

path = u'C:\\TempRandom\\utf8-1\\boo\\hi это русский end - Copy.txt'
# Clean path when printing since Windows terminal only supports ASCII:
print "Path: "+path.encode(sys.stdout.encoding, errors='replace')
# Test that you can open it with normal Python open:
normal_fp = open (path, mode='r')
normal_fp.close()

fileH = win32file.CreateFile( path, win32file.GENERIC_READ, \
                            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, \
                            None, # No special security requirements \
                            win32file.OPEN_EXISTING, # expect the file to exist. \
                            0, # Not creating, so attributes dont matter. \ 
                            None ) # No template file       
result, msg =  win32file.ReadFile(fileH, 1000, None)
print "File Content >>"
print msg
4

1 回答 1

1

解决方案是使用CreateFileW而不是CreateFilefileH = win32file.CreateFileW

具有讽刺意味的是,CreateFile 的文档说它支持 PyUnicode 字符串,但底层的 Windows 函数不支持,除非您使用 CreateFileW。CreateFileW 支持 unicode 的宽字符。

感谢这篇讨论 CreateFile 的 C 版本的帖子: 如何使用 CreateFile() API 函数打开名为

于 2013-10-04T16:51:39.257 回答