Created
February 26, 2026 00:06
-
-
Save jtbr/4f7bb78fd3dd9dceab222f5090e0f18a to your computer and use it in GitHub Desktop.
Find whether you can write to a path without actually doing so (in python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from pathlib import Path | |
| def is_writable(path: Path) -> tuple[bool,str]: | |
| """Determines if path is writeable without actually writing to it. | |
| Return True if the process can write to path, and False otherwise, along with a useful error message.""" | |
| if path.exists(): | |
| if not os.access(path, os.W_OK): | |
| return False, f"Cannot write to {path}: permission denied" | |
| else: | |
| parent = path.parent | |
| if not parent.is_dir(): | |
| return False, f"Cannot write to {path}: directory {parent} does not exist" | |
| if not os.access(parent, os.W_OK): | |
| return False, f"Cannot write to {path}: permission denied writing to {parent}" | |
| return True, f"{path} is writable" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment