Recipe 2.25. Changing File Attributes on WindowsCredit: John Nielsen ProblemYou need to set the attributes of a file on Windows; for example, you may need to set the file as read-only, archived, and so on. SolutionPyWin32's win32api module offers a function SetFileAttributes that makes this task quite simple: import win32con, win32api, os # create a file, just to show how to manipulate it thefile = 'test' f = open('test', 'w') f.close( ) # to make the file hidden...: win32api.SetFileAttributes(thefile, win32con.FILE_ATTRIBUTE_HIDDEN) # to make the file readonly: win32api.SetFileAttributes(thefile, win32con.FILE_ATTRIBUTE_READONLY) # to be able to delete the file we need to set it back to normal: win32api.SetFileAttributes(thefile, win32con.FILE_ATTRIBUTE_NORMAL) # and finally we remove the file we just made os.remove(thefile) DiscussionOne interesting use of win32api.SetFileAttributes is to enable a file's removal. Removing a file with os.remove can fail on Windows if the file's attributes are not normal. To get around this problem, you just need to use the Win32 call to SetFileAttributes to convert it to a normal file, as shown at the end of this recipe's Solution. Of course, this should be done with caution, since there may be a good reason the file is not "normal". The file should be removed only if you know what you're doing! See AlsoThe documentation on the win32file module at http://ASPN.ActiveState.com/ASPN/Python/Reference/Products/ActivePython/PythonWin32Extensions/win32file.html. |