2

I'm tying to delete a file using this code and I am getting "YES File is present" but on os.remove I am getting error.

Code

os.chdir('C:/Users/USERNAME/Desktop/WhatsApp Documents/7K1')
    if os.path.exists("file.jpg"):
        print('YES File is Present')
        os.remove('file.jpg')
    else:
        print('NO')

Error

PermissionError: [WinError 5] Access is denied: 'file.jpg'
  • The code looks fine (it has a tiny race condition, but itll probably always work). Windows isn't letting you do this for some reason. Does deleting the file by hand work? – Ben Dec 15 '19 at 07:23
  • Yes It allows me to delete it manually – Ahmad Arshi Dec 15 '19 at 07:28
  • Does this answer your question? [Deleting directory in Python](https://stackoverflow.com/questions/1889597/deleting-directory-in-python) – sahasrara62 Dec 15 '19 at 08:34

2 Answers2

0

try this :

import os  
os.remove("ChangedFile.csv")
print("File Removed!")
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
Nithees balaji
  • 148
  • 1
  • 11
0

Can you try running the python program as administrator. Your code looks fine the issue is you dont have permission to delete the file.

If you are executing the program from command prompt launch it with run as administrator and run the programme

ArunJose
  • 1,999
  • 1
  • 10
  • 33