Using the fs module¶
Take ownership of a file¶
Take ownership of a file to which you have no other access.
from __future__ import with_statement
from winsys import security, fs
f = fs.file("c:/temp/tim.txt")
with security.change_privileges([security.PRIVILEGE.TAKE_OWNERSHIP]):
f.take_ownership()
assert f.security("O").owner == security.me()
The Entry.take_ownership()
method assumes that you have no existing
access to the object, so does not attempt to read its security at all
since this would probably fail. If you do not even have permission
to set the owner entry in the security descriptor you need to enable
the SeTakeOwnership privilege in your token. Best practice is to
enable privileges for only as long as you need them, so the security.changed_privileges()
is a context manager which reverses the privilege changes once it exits.
Find the sizes of top-level directories¶
For a given root directory, find the total size taken by all the files in each of its top-level subdirectories, and display them in descending order of size.
import operator
from winsys import dialogs, fs, utils
[root] = dialogs.dialog(
"Find top-level sizes",
("Start from", "", dialogs.get_folder)
)
sizes = dict(
(d, sum(f.size for f in d.flat()))
for d in fs.dir(root).dirs()
)
for d, size in sorted(sizes.items(), key=operator.itemgetter(1), reverse=True):
print d.name, "=>", utils.size_as_mb(size)
The dialogs.dialog()
function sets up a simple dialog box
requesting the name of the root directory (offering a push-button
for a standard selection dialog). Then the Dir.dirs()
method
iterates over all subdirectories of its directory, and Dir.flat()
iterates over all the files underneath a directory from which we can
fetch their (compressed) size and sum them all up.
The rest is mostly standard Python gimmickry with sorting dictionaries
etc. utils.size_as_mb()
provides a more human-readable
version of a number of bytes.