PermissionError, what it means and how to fix it

The file was found; the operating system refused to let the program touch it in the requested way. On Windows the most common story is a lock: a CSV or Excel file still open in a spreadsheet cannot be overwritten. On Linux and macOS it is usually ownership and mode bits, or the program reaching into a folder (system directories, another user's home) it has no rights to.

What it looks like

open("report.csv", "w")     # report.csv is open in Excel

Traceback (most recent call last):
  File "main.py", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'report.csv'

# fixed: close the file in the other program first,
# or write to a name it does not hold open

The fix, in order

  1. Close the file in every other program. On Windows, a file open in Excel, a preview pane, or an editor is locked against writing. This single step resolves the majority of desktop cases.
  2. Check the mode you opened with. Writing to a file opened with "r" raises PermissionError on some paths and a clearer io error on others; appending needs "a", writing needs "w". Reading a folder as if it were a file raises a sibling error (IsADirectoryError on Linux, PermissionError on Windows).
  3. Check the file's own protection. Read-only attribute set (common on files copied from archives, email, or version control) blocks writing. Clear it, or write to a new file instead.
  4. Work in a folder you own. Programs launched from protected locations (Program Files, system folders, another user's directory) cannot write outputs next to themselves. Write results to your documents or a working folder.
  5. On Linux/macOS, read the mode bits: ls -l shows owner and permissions. Fix with chmod/chown only on files that are yours; if the file belongs to the system, the real fix is not to write there.

If it still happens

If permissions look right and nothing holds the file, antivirus and endpoint protection on managed machines sometimes block script interpreters from writing executables or scripts. The tell is that the same code works on an unmanaged machine; the remedy is an allowlist entry from IT, not weaker local settings.

Common questions

Why does Windows raise PermissionError for a file open in Excel, but Linux doesn't? Windows enforces sharing locks: an application can hold a file so that writers are refused. Linux traditionally lets you write (even delete) files another program has open. The same script can therefore run on Linux and fail on Windows with no bug in the script.

Should I just run Python as administrator or with sudo? That masks the cause and creates files owned by the administrator that your normal account later cannot touch. Fix the actual lock, mode, or location; elevation is the right answer only for programs that genuinely administer the system.

Related errors

FileNotFoundError · OSError · BrokenPipeError