4

My understanding is that, in order to delete a file, I need write permission to the parent folder (for Windows). I don't need write permission to the file itself.

But os.remove gives me "[WinError 5] Access is denied". I can delete that file via the Windows explorer with my user.

shutil.copy copies a file to a folder without problems, but running the script again gives a "[Errno 13] Permission denied", because the file is read-only and can not be overwritten. It makes no sense that I can create files but not delete those afterwards. Fix is to use shutil.copyfile, because then the destination file has no permissions and it can be overwritten in the next run, but then this won't work if the file already exists with the permissions.

How do I delete a file with only read permissions but write permission to the parent folder?

Python 3.3.2

cubei
  • 323
  • 3
  • 12
  • Interesting that you get two different errors. For `[Errno 13] Permission denied`, you don't have the file opened with anything do you? – roganjosh Aug 24 '18 at 07:38
  • There's also some info [here](https://stackoverflow.com/questions/4829043/how-to-remove-read-only-attrib-directory-with-python-in-windows) that might be useful – roganjosh Aug 24 '18 at 07:40
  • @roganjosh That's because the copy function tries to open the file with write permission. The error comes in this line: with open(dst, 'wb') as fdst – cubei Aug 24 '18 at 08:29

1 Answers1

5

read-only attribute can be cleared like this.

import os
import stat
os.chmod(filePath, stat.S_IWRITE)
cubei
  • 323
  • 3
  • 12