Wednesday, May 5, 2010

Python: Get and Set FileAttributes

Problem Statement:
Getting and Setting File Attributes in python

Code Implementation:
import os, win32file, win32con, win32api
import sys

def Getfileattrib(filepath):
""" Will check for a particular attribute is enabled for a file or not"""
try:
attributes = []
attrib = win32file.GetFileAttributes(filepath)
if not os.path.isfile(filepath):
print filepath + ": File Not Found"
print "Exiting..."
sys.exit(1)
if((attrib & win32con.FILE_ATTRIBUTE_ARCHIVE)):
attributes.append("A")
if((attrib & win32con.FILE_ATTRIBUTE_SYSTEM)):
attributes.append("S")
if((attrib & win32con.FILE_ATTRIBUTE_HIDDEN)):
attributes.append("H")
if((attrib & win32con.FILE_ATTRIBUTE_READONLY)):
attributes.append("R")
return attributes
except Exception:
raise

def Setfileattrib(filepath, attributes):
""" Will set attributes for a file taking list of attributes in a list"""
try:
if not os.path.isfile(filepath):
print filepath + ": File Not Found"
print "Exiting..."
for attribute in attributes:
os.system("attrib +%s %s" % (attribute.upper(), filepath))
except Exception:
raise

No comments: