How do you use Python to get or change read-only/writeable access on files in Windows? The Python docs don't answer this in a direct manner. Here's one option using only the standard library.
import os, statYou may prefer the pywin32 extensions for this sort of thing...
myFile = r'C:\stuff\grail.txt'
fileAtt = os.stat(myFile)[0]
if (not fileAtt & stat.S_IWRITE):
# File is read-only, so make it writeable
os.chmod(myFile, stat.S_IWRITE)
else:
# File is writeable, so make it read-only
os.chmod(myFile, stat.S_IREAD)
import win32api, win32conOr, more concisely with win32:
myFile = r'C:\stuff\grail.txt'
fileAtt = win32api.GetFileAttributes(myFile)
if (fileAtt & win32con.FILE_ATTRIBUTE_READONLY):
# File is read-only, so make it writeable
win32api.SetFileAttributes(myFile, ~win32con.FILE_ATTRIBUTE_READONLY)
else:
# File is writeable, so make it read-only
win32api.SetFileAttributes(myFile, win32con.FILE_ATTRIBUTE_READONLY)
roAtt = win32api.GetFileAttributes(myFile) & win32con.FILE_ATTRIBUTE_READONLYUsing win32 you can also set other Windows file attributes (unlike os.chmod), but read/write is usually all I care about.
win32api.SetFileAttributes(myFile, ~roAtt)
1 comments:
You can use the dos attrib command:
>>>os.system('attrib -R %s' % myFile)
Post a Comment