Python Permission Denied When Writing to file and not when read

Viewed 1185

Python error when opening file with:

f = open(file, "w")

but it does open with:

f = open(file, "r")

1- file is closed when running my app

2- app is running as administrator

3- file is not set as read only and should have the write permission (using windows)

and still I am getting this error:

[Errno 13] Permission denied: 'file.txt'

I couldn't fix the problem if anyone have any idea please let me know.

1 Answers

PermissionError: [errno 13] permission deniederror occurs when you try to access a file from Python without having the necessary permissions.

SOLUTIONS N.1

Try specifying the full path to the file. The error could be that when not using a full path, Python uses the current directory and that is different from the default.

f = open('C:\my folder\myOutput.txt', 'w')

SOLUTION N.2

path = Path("path/to/my/file.txt")
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as file:
    ...

SOLUTION N.3

import os

path = r"my/path/to/file.txt"
assert os.path.isfile(path)
with open(path, "r") as f:
    pass

SOLUTION N. 4

from os import path

file_path = path.relpath("xxx/file.txt")
with open(file_path) as f:
    <do stuff>
Related