0

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?

hbhutta
  • 15
  • 5
  • 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). – MegaIng Sep 03 '23 at 04:32
  • Ok, that clarifies things. I was confused about that. Thanks. I'm going to accept the answer below. – hbhutta Sep 03 '23 at 04:33

2 Answers2

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)
am33t
  • 1
  • 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:
    .
    .
    .
    .
Stitt
  • 406
  • 2
  • 8
  • 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. – hbhutta Sep 03 '23 at 04:31
  • Please accept as answer if this helped – Stitt Sep 03 '23 at 04:32