0

I am working on a program that would:

  1. Process a file
  2. If no error move into Processed Directory (using postSuccessActions below)
  3. If error move into Error Directory

Code:

def postSuccessActions(self, fileName):
    basedir = os.path.dirname(fileName)
    dest = os.path.join(os.path.dirname(fileName), 'Processed\\Original\\')
    self._createPath(dest) #custom function that create only if path doesn't exist
    shutil.move(fileName, dest)

Issue: The problem is that shutil.move creates a copy of the file in the destination folder and then tries to delete it but fails with error below:

WindowsError: [Error 5] Access is denied: '<filename here>'

Now I don't want to come this far if the user has no delete permission on the file being processed. I am looking for a way to check if a given file can be deleted before doing any processing with it. How do I do it with python on windows?

user3885927
  • 3,363
  • 2
  • 22
  • 42
  • I would still think the process you are looking for is attempt move and error on error. You can try a rename, and then fall back to a copy/delete operation. You can always delete your copy if that is part of the logic you need. – Clarus Sep 29 '14 at 18:01
  • You could use subprocess to call out to the native "move" command which will do the check for you. – tdelaney Sep 29 '14 at 18:11
  • @Claris, Seems like you are suggesting to make an actual move. Isn't there a better way to check for permissions? – user3885927 Sep 29 '14 at 18:14
  • @user: You can always check permissions, but nothing will guarantee that your move will succeed. The approach I suggested was to mitigate unintended side effects by trying rename then copy/delete when that doesn't work. – Clarus Sep 29 '14 at 18:23
  • Perhaps [this](http://stackoverflow.com/questions/539133/python-test-directory-permissions) question may help you – Mauro Baraldi Sep 29 '14 at 18:33
  • @MauroBaraldi, thank you but that doesn't help much in my case. I am looking for delete permissions so listdir will not work. – user3885927 Sep 29 '14 at 19:35
  • [`MoveFile`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365239%28v=vs.85%29.aspx) (or `MoveFileEx` with `MOVEFILE_COPY_ALLOWED`) can't even check whether deleting the original will succeed if it has to copy the file. However, it does call `SetFileAttributes` to clear the read-only attribute if the first call to `DeleteFile` fails. – Eryk Sun Sep 30 '14 at 02:30

0 Answers0