Search code examples
pythonattributesfile-attributesbitflags

Python: Setting Multiple Attributes for a file (e.g. System, Hidden)


What is the way to set multiple file-attributes using Python?

E.g. I want to set a file's attribute to System, Hidden.

I can use something like below, but it will just set just one attributes, and overwrite the previous write:

import win32con, win32api, os

filename = "some file name"

win32api.SetFileAttributes(filename,win32con.FILE_ATTRIBUTE_SYSTEM)
win32api.SetFileAttributes(filename,win32con.FILE_ATTRIBUTE_HIDDEN)

This will end up with just Hidden attribute.

How do you set both attributes at once? Thanks.


Solution

  • OK, here is the solution. I made it generic for general use.

    import win32api
    ## If need to install pywin if not already to get win32api
    
    ## Define constants for Windows file attributes
    FILE_ATTRIBUTE_READONLY = 0x01
    FILE_ATTRIBUTE_HIDDEN = 0x02
    FILE_ATTRIBUTE_SYSTEM = 0x04
    FILE_ATTRIBUTE_DIRECTORY = 0x10
    FILE_ATTRIBUTE_ARCHIVE = 0x20
    FILE_ATTRIBUTE_NORMAL = 0x80
    FILE_ATTRIBUTE_TEMPORARY = 0x0100
    
    ## Combine all the attributes you want using bitwise-Or (using the pipe symbol)
    Attribute = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM
    
    filename="Your-filename-goes-here"
    
    win32api.SetFileAttributes(filename,Attribute)
    
    ## Check that the attribute is set.
    ## You can also right click on the file in windows explorer and 
    ## look under Details tab.
    
    print win32api.GetFileAttributes(filename)