How to fix PermissionError when working with files in Python
The aim of this page📝 is to explain how to fix a PermissionError
when working with files in Python. Previously I showed How to Write Unit Tests for Custom Context Manager in Python which is just an illustration of fixing little problems along the way.
1 min readJul 13, 2023
- The error occurs when a file is being used by another process and cannot be accessed.
- This can happen if the file is not closed properly before it is removed.
- To fix the issue, make sure to close the file before removing it.
- Here’s the original code that caused the error:
""" CODE """
@contextmanager
def handle_patching(schema: dict) -> None:
try:
with open("temp_schema.json", mode="wt", encoding="utf-8") as temp_schema:
json.dump(schema, temp_schema, indent=4)
yield
finally:
# TODO: Send a PUT request of the patched schema
os.remove("temp_schema.json")
""" TEST FAILING WITH `PermissionError` """
def test_handle_patching():
TEMP_SCHEMA_FILENAME = "temp_schema.json"
schema = {}
with push_and_pop_path(MODULE_PATH):
with handle_patching(schema):
assert TEMP_SCHEMA_FILENAME in os.listdir()
assert "{}" in open(TEMP_SCHEMA_FILENAME).read()
assert TEMP_SCHEMA_FILENAME not in os.listdir()
- And here’s an example of how to fix the issue:
def test_handle_patching():
TEMP_SCHEMA_FILENAME = "temp_schema.json"
schema = {}
with push_and_pop_path(MODULE_PATH):
with handle_patching(schema):
assert TEMP_SCHEMA_FILENAME in os.listdir()
with open(TEMP_SCHEMA_FILENAME) as f:
assert "{}" in f.read()
assert TEMP_SCHEMA_FILENAME not in os.listdir()
- This ensures that the file is closed before it is removed and prevents the
PermissionError
.