Welcome, guest | Sign In | My Account | Store | Cart

The win32api module offers SetFileAttributes whiles allows you to make changes to a file in windows. You can set a file to be read only, archive, hidden, etc. The function is simple and convenient to use.

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import win32con, win32api,os

file='test'
f=open('test','w')
f.close()

#make the file hidden
win32api.SetFileAttributes(file,win32con.FILE_ATTRIBUTE_HIDDEN)

#make the file read only
win32api.SetFileAttributes(file,win32con.FILE_ATTRIBUTE_READONLY)

#to force deletion of a file set it to normal
win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_NORMAL)
os.remove(file) 

One interesting use of win32api.SetFileAttributes is to force removal of a file. Removing with os.remove can fail on windows, if it's attributes are not normal. To get around this problem you need to use the win32 call to SetFileAttributes to convert it to a normal file. Of course, this should be done with caution, since there probably a good reason the file is not normal.