0
0
PythonHow-ToBeginner · 3 min read

How to Change File Permissions in Python Easily

You can change file permissions in Python using the os.chmod(path, mode) function, where path is the file path and mode is the permission setting in octal format. Use permission codes like 0o644 for read/write by owner and read-only for others.
📐

Syntax

The os.chmod(path, mode) function changes the permissions of the file at path. The mode is an integer representing the permission bits, usually written in octal (base 8) format.

  • path: String path to the file.
  • mode: Permission bits like 0o644, 0o755.
python
import os

os.chmod('filename.txt', 0o644)
💻

Example

This example creates a file, changes its permissions to read/write for owner and read-only for others, then prints confirmation.

python
import os

filename = 'example.txt'

# Create a file
with open(filename, 'w') as f:
    f.write('Hello, world!')

# Change permissions to rw-r--r-- (owner read/write, others read)
os.chmod(filename, 0o644)

print(f"Permissions for '{filename}' changed to 0o644")
Output
Permissions for 'example.txt' changed to 0o644
⚠️

Common Pitfalls

Common mistakes include:

  • Using decimal numbers instead of octal for mode. Always prefix with 0o for octal.
  • Trying to change permissions on a file that does not exist, which raises FileNotFoundError.
  • Running on Windows where permission bits behave differently or are ignored.
python
import os

filename = 'missing.txt'

# Wrong: decimal instead of octal
# os.chmod(filename, 644)  # This is decimal 644, not octal

# Correct:
# os.chmod(filename, 0o644)  # Use octal with 0o prefix

try:
    os.chmod(filename, 0o644)
except FileNotFoundError:
    print(f"File '{filename}' not found. Cannot change permissions.")
Output
File 'missing.txt' not found. Cannot change permissions.
📊

Quick Reference

Permission CodeMeaning
0o644Owner read/write, others read
0o600Owner read/write, others no access
0o755Owner read/write/execute, others read/execute
0o700Owner read/write/execute, others no access

Key Takeaways

Use os.chmod(path, mode) with mode in octal (e.g., 0o644) to change file permissions.
Always prefix permission codes with 0o to specify octal numbers in Python.
Check that the file exists before changing permissions to avoid errors.
File permission changes may behave differently on Windows compared to Unix-like systems.