44

I want to create a file and write some integer data to it in python. For example, I have a variable abc = 3 and I am trying to write it to a file (which doesn't exist and I assume python will create it on its own):

fout = open("newfile.dat", "w")
fout.write(abc)

First, will python create a newfile.dat on its own? Secondly, it's giving me this error:

IOError: [Errno 13] Permission denied: 'newfile.dat'

What's wrong here?

user1921843
  • 667
  • 2
  • 8
  • 13

11 Answers11

26

Please close the file if its still open on your computer, then try running the python code. I hope it works

Aseem
  • 5,848
  • 7
  • 45
  • 69
  • The "w" mode looks correct for creating a file. If not an open file, perhaps it's a permissions issue with the working directory? What OS is the OP using? – killthrush Jul 28 '15 at 22:56
  • If running something headlessly / opening with python, make sure there is a file.close() – chaytan Sep 28 '21 at 21:42
17

This also happens when you attempt to create a file with the same name as a directory:

import os

conflict = 'conflict'

# Create a directory with a given name
try: 
    os.makedirs(conflict)
except OSError:
    if not os.path.isdir(conflict):
        raise

# Attempt to create a file with the same name
file = open(conflict, 'w+')

Result:

IOError: [Errno 13] Permission denied: 'conflict'
Derek
  • 1,104
  • 13
  • 35
13

I've had the same issue using the cmd (windows command line) like this

C:\Windows\System32> "G:\my folder\myProgram.py"

Where inside the python file something like this

myfile = open('myOutput.txt', 'w')

The error was that when you don't use a full path, python would use your current directory, and because the default directory on cmd is

C:\Windows\System32 

that won't work, as it seems to be write-protected and needs permission & confirmation form an administrator

Instead, you should use full paths, for example:

myfile = open('G:\my folder\myOutput.txt', 'w')
Omar
  • 607
  • 3
  • 8
  • 18
  • 1
    I just wanted to add that was my case. I was using Windows Task Scheduler and a .bat file to run my Python script, was getting the permission error until I added the full path for the file. – Jacob Boyd Mar 20 '20 at 12:23
  • use os.chdir(path) to set the cwd to where the file sits – Pythonic Oct 08 '20 at 10:48
  • Though not the case in the OP's question, you can also get a permission error if you specify an existing path without appending a file name as well. It sounds basic, but where variables for paths exist, it can be easy to forget to append the filename to create the full path.. (*blushes*) – kowpow Apr 14 '23 at 08:50
  • Perhaps see also [What exactly is current working directory?](https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory/66860904) – tripleee May 19 '23 at 07:05
11

Permission denied simply means the system is not having permission to write the file to that folder. Give permissions to the folder using "sudo chmod 777 " from terminal and try to run it. It worked for me.

Edwin Rapheal
  • 131
  • 1
  • 4
  • It may also mean that the file does exist but is not writable by you: in order to write to an already existing file you must first "delete" its contents, which implies write permissions to the existing file... I got into this situation today and I spent 30 minutes figuring what was happening, when it was this "simple". – Le Sir Dog Mar 16 '22 at 17:32
6

I write python script with IDLE3.8(python 3.8.0) I have solved this question: if the path is shelve.open('C:\\database.dat') it will be PermissionError: [Errno 13] Permission denied: 'C:\\database.dat.dat'. But when I test to set the path as shelve.open('E:\\database.dat') That is OK!!! Then I test all the drive(such as C,D,F...) on my computer,Only when the Path set in Disk

C:\\

will get the permission denied error. So I think this is a protect path in windows to avoid python script to change or read files in system Disk(Disk C)

  • 1
    I'm having the same issue. How can you get write permission to C drive? I've tried masking without any luck. I'm making a tool that I'd like to install in `C:\Program Files` by default – Mike Bourbeau Sep 01 '20 at 23:30
  • I see the same in Windows 10. Trying to change permission to the folder under `C:` via git bash does not work. Fortunately, I have another drive mounted on `D:` and can write to that disk. – arun Nov 15 '20 at 00:55
3

In order to write on a file by using a Python script, you would have to create a text file first. Example A file such as C:/logs/logs.txt should exist. Only then the following code works:

logfile=open(r"C:/logs/logs.txt",'w')

So summary.

  1. A text file should exist on the specified location
  2. Make sure you close the file before running the Python script.
Yaser Darzi
  • 1,480
  • 12
  • 24
2

To answer your first question: yes, if the file is not there Python will create it.

Secondly, the user (yourself) running the python script doesn't have write privileges to create a file in the directory.

mavili
  • 3,385
  • 4
  • 30
  • 46
  • It was a permission error which is fixed now but still this error is coming up: TypeError: expected a character buffer object – user1921843 Aug 30 '13 at 09:27
  • 1
    To write something other than a string, it needs to be converted to a string first. See: http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects – Robert Caspary Aug 30 '13 at 09:34
  • to add to @RobertCaspary 's comment, you can use `str(abc)` to convert to string. so `fout.write(str(abc))` – mavili Aug 30 '13 at 09:43
  • 2
    Different issue now. It should be a different question ;) – Paco Aug 30 '13 at 09:48
  • How can I get around the issue of write permissions denied after the creation of a directory from python? – psiyumm May 12 '14 at 17:11
1

If you are executing the python script via terminal pass --user to provide admin permissions.

Worked for me!

If you are using windows run the file as admin.

If you are executing via cmd, run cmd as admin and execute the python script.

Santosh Santu
  • 91
  • 1
  • 11
0

Make sure that you have write permissions for that directory you were trying to create file by properties

Anto
  • 610
  • 5
  • 13
0

I have had this same issue and i figured that the file is open in my pc and hence the permission denied issue , once i close the file . It would work

0

I know that probably you've already solve this issue, but just in case: My issue was related with the "path" definition when trying to dynamically create folders and sub-folders. I try to pass the "path" directly to the df.to_excel, but you need to first add the file name into the path:

year = str(date_input.year)
month = str(date_input.month)
path = Path('../Project_Files/' + year + '/' + month)
if not os.path.isdir(path):
    path.mkdir(parents=True, exist_ok=True)
else:
    for f in os.listdir(path):
        os.remove(os.path.join(path, f))
path_final = os.path.join(path,'excel.xlsx')
df.to_excel(path_final, index=False)

And it works, without the error of "Permission denied"

ruben
  • 11
  • 3