Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - Set "hide" attribute on folders in windows OS?

Trying to hide folder without success. I've found this :

import ctypes
ctypes.windll.kernel32.SetFileAttributesW('G:Dirfolder1', 2)

but it did not work for me. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...