我使用以下代码在Windows上执行某些文件系统操作(复制/移动/重命名文件和文件夹)。 此代码需要pywin32。
from win32com.shell import shell, shellcon
from ctypes.wintypes import HWND, UINT, LPCWSTR, BOOL, WORD
from ctypes import c_void_p, Structure, windll, POINTER, byref
src = unicode(os.path.abspath(_src_) + '\0', 'utf-8')
dest = unicode(os.path.abspath(_dest_) + '\0', 'utf-8')
class SHFILEOPSTRUCTW(Structure):
_fields_ = [("hwnd", HWND),
("wFunc", UINT),
("pFrom", LPCWSTR),
("pTo", LPCWSTR),
("fFlags", WORD),
("fAnyOperationsAborted", BOOL),
("hNameMappings", c_void_p),
("lpszProgressTitle", LPCWSTR)]
SHFileOperationW = windll.shell32.SHFileOperationW
SHFileOperationW.argtypes = [POINTER(SHFILEOPSTRUCTW)]
args = SHFILEOPSTRUCTW(wFunc=UINT(op), pFrom=LPCWSTR(src), pTo=LPCWSTR(dest), fFlags=WORD(flags), fAnyOperationsAborted=BOOL())
result = SHFileOperationW(byref(args))
aborted = bool(args.fAnyOperationsAborted)
if not aborted and result != 0:
# Note: raising a WindowsError with correct error code is quite
# difficult due to SHFileOperation historical idiosyncrasies.
# Therefore we simply pass a message.
raise WindowsError('SHFileOperationW failed: 0x%08x' % result)
标志始终为:shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI | shellcon.FOF_NOCONFIRMMKDIR
op用于例如:shellcon.FO_COPY
我遇到的问题是,有时这个函数会给我错误:
ArgumentError: argument 1: <type 'exceptions.TypeError'>: expected LP_SHFILEOPSTRUCTW instance instead of pointer to SHFILEOPSTRUCTW
特别是在处理很长的路径时(例如len(dest)=230
)
我在这里做错了什么?
[编辑]
有shell.SHFileOperation
但我们需要使用自定义包装器SHFileOperationW
来支持unicodes。
[EDIT2]
正如Barmak Shemirani所写,在python3中你可以简单地使用shell.SHFileOperation,它可以与任何特殊的unicode字符一起使用。 如果我在python2中找到解决方法,我将在这里分享。