Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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:
    .
    .
    .
    .
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading