Skip to content

Commit f96555e

Browse files
committed
os_lib: add os.chmod and os.access example
1 parent 227e622 commit f96555e

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

os_lib/03_chmod.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import os
2+
import sys
3+
import stat
4+
5+
if len(sys.argv) == 1:
6+
filename = __file__
7+
else:
8+
filename = sys.argv[1]
9+
10+
# Determine what permissions are already set using stat
11+
permissions = stat.S_IMODE(os.stat(filename).st_mode)
12+
13+
if not os.access(filename, os.X_OK):
14+
print('Adding execute permission')
15+
new_permissions = permissions | stat.S_IXUSR
16+
else:
17+
print('Removing execute permission')
18+
# use xor to remove the user execute permission
19+
new_permissions = permissions ^ stat.S_IXUSR
20+
21+
os.chmod(filename, new_permissions)
22+
23+
print('Readable:', os.access(filename, os.R_OK))
24+
print('Writable:', os.access(filename, os.W_OK))
25+
print('Executable:', os.access(filename, os.X_OK))

os_lib/test_file.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Some content for testing purposes

0 commit comments

Comments
 (0)