Getting PermissionError when trying to create a file in a directory

I know this is probably a very common question, and I’ve already seen posts, here, here and here asking similar questions. But these posts relate to writing to a file. I want to create a file in a specific directory.

Specifically, I am trying to populate a folder with many .mp3 files.

Here’s what I’ve tried so far:

import os 

if not os.path.isdir('testing'):
    os.mkdir('testing')

dir_path="testing"
file_path="foo.mp3"
with open(dir_path, 'x') as f:
    f.write(file_path, os.path.basename(file_path))

I tried ‘x’ because I saw here that this creates a file and raises an error if the file does not exist. I am not getting this error, but I am getting this:

PermissionError: [Errno 13] Permission denied: 'testing'

I saw in the first post I’ve linked that this happens when I’m trying to “open a file, but my path is a folder”. I am not trying to open a file though, I am trying to open a directory and add a file to that directory.

I also looked at the answer to this post, but the answerer is writing to a file not creating a file.

I might be overcomplicating things. Everything I could look up online has to do with writing to a file, not creating a file. I’m sure the task is very simple. What have I done wrong?

  • It doesn’t make sense to “open” directories using the open function. open only works for files (as some of the links you provided explain).

    – 

  • Ok, that clarifies things. I was confused about that. Thanks. I’m going to accept the answer below.

    – 

You need to open your file via a complete path with the ‘w’ option. This will create the file for you and allow you to write, as at the moment you are attempting to write file contents to a directory.

import os

dir_path="testing"
file_path="foo.mp3"

if not os.path.isdir(dir_path):
    os.mkdir(dir_path)

write_path = os.path.join(dir_path, file_path)
with open(write_path, 'w') as f:
    .
    .
    .
    .

Try This: (You basically need to create a full path before populating. I have used .join() here)

import os 

dir_path="testing" 
file_path="foo.mp3"

if not os.path.isdir(dir_path):
    os.mkdir(dir_path)

full_file_path = os.path.join(dir_path, file_path)

with open(full_file_path, 'w') as f:
    f.write(file_path)

Leave a Comment