1

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?

2
  • 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). Commented Sep 3, 2023 at 4:32
  • Ok, that clarifies things. I was confused about that. Thanks. I'm going to accept the answer below. Commented Sep 3, 2023 at 4:33

2 Answers 2

0

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:
    .
    .
    .
    .
Sign up to request clarification or add additional context in comments.

1 Comment

I think you're right because I just tried this one line: f = open('testing/afjahf.mp3', 'x') and it created the file in the specified directory.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.