There are two things wrong with your code, both having to do with the folder name literal. The SetFileAttributesW()
function requires a Unicode string argument. You can specify one of those by prefixing a string with the character u
. Secondly, any literal backslash characters in the string will have to be doubled or you could [also] add an r
prefix to it. A dual prefix is used in the code immediately below.
import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02
ret = ctypes.windll.kernel32.SetFileAttributesW(ur'G:Dirfolder1',
FILE_ATTRIBUTE_HIDDEN)
if ret:
print('attribute set to Hidden')
else: # return code of zero indicates failure -- raise a Windows error
raise ctypes.WinError()
You can find Windows' system error codes here. To see the results of the attribute change in Explorer, make sure its "Show hidden files" option isn't enabled.
To illustrate what @Eryk Sun said in a comment about arranging for the conversion to Unicode from byte strings to happen automatically, you would need to perform the following assignment before calling the function to specify the proper conversion of its arguments. @Eryk Sun also has an explanation for why this isn't the default for pointers-to-strings in the W
versions of the WinAPI functions -- see the comments.
ctypes.windll.kernel32.SetFileAttributesW.argtypes = (ctypes.c_wchar_p, ctypes.c_uint32)
Then, after doing that, the following will work (note that an r
prefix is still required due to the backslashes):
ret = ctypes.windll.kernel32.SetFileAttributesW(r'G:Dirfolder1',
FILE_ATTRIBUTE_HIDDEN)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…