-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpathlib_chmod.py
More file actions
28 lines (23 loc) · 828 Bytes
/
pathlib_chmod.py
File metadata and controls
28 lines (23 loc) · 828 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import os
import pathlib
import stat
# Create a fresh test file.
f = pathlib.Path("pathlib_chmod_example.txt")
if f.exists():
f.unlink()
f.write_text("contents")
# Determine what permissions are already set using stat.
existing_permissions = stat.S_IMODE(f.stat().st_mode)
print("Before: {:o}".format(existing_permissions))
# Decide which way to toggle them.
if not (existing_permissions & os.X_OK):
print("Adding execute permission")
new_permissions = existing_permissions | stat.S_IXUSR
else:
print("Removing execute permission")
# use xor to remove the user execute permission
new_permissions = existing_permissions ^ stat.S_IXUSR
# Make the change and show the new value.
f.chmod(new_permissions)
after_permissions = stat.S_IMODE(f.stat().st_mode)
print("After: {:o}".format(after_permissions))