gpt4 book ai didi

Python win32file.CreateFile 与 Unicode 字符

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:29 31 4
gpt4 key购买 nike

当尝试使用 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)

最佳答案

解决方案是使用 CreateFileW 而不是 CreateFile:fileH = win32file.CreateFileW

讽刺的是,documentation for CreateFile说它支持 PyUnicode 字符串,但底层 Windows 函数不支持,除非您使用 CreateFileW 。 CreateFileW 支持 unicode 的宽字符。

感谢这篇文章讨论 CreateFile 的 C 版本: How do I open a file named 𤭢.txt with CreateFile() API function?

关于Python win32file.CreateFile 与 Unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186494/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com