0

I created a pdf and a folder. The pdf is inside this folder. When re_running the code this is supposed to check if this folder exists and then if so, remove it and create it again (replacing it). If the folder does not exist then just create it normally. I am running into a permission error . I am wondering wow I can achieve this.

See code below:

    newpath = rf'C:\Users\{username}\Desktop\Output Folder(MC)-{jobnumber}'
    if  os.path.exists(newpath):
        os.remove(newpath)
        os.makedirs(newpath)
    else:
        os.makedirs(newpath)

The full error is:

os.remove(newpath) PermissionError: [WinError 5] Access is denied: 'C:\\Users\\rherencia\\Desktop\\Output Folder(MC)-ITI-034214-1-1'

Barmar
  • 741,623
  • 53
  • 500
  • 612
RafaelTech
  • 19
  • 7
  • 1
    You need write permission to the containing directory to remove a subdirectory. So you don't have write permission to `Desktop`. – Barmar Aug 01 '23 at 20:05
  • 3
    `os.remove()` won't delete directories. `os.rmdir()` would work if you know the directory is empty. `shutil.rmtree()` handles the general case. – jasonharper Aug 01 '23 at 20:07
  • This should help: https://stackoverflow.com/a/44713937/12317368 – Ro.oT Aug 01 '23 at 20:08

0 Answers0