简体   繁体   中英

Why os.rename sometimes returns error access is denied python

I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,

 [Error 5] Access is denied

But all other times its working fine. Code,

try:
  if(os.path.exists(Downloaded_Path)):
    os.rename(Downloaded_Path, Downloaded_Path + "_ByClientTool")
except Exception,e:
  print "Error !!", str(e)
  return 1

The error means that the user account that the scheduler uses to run the program does not have permissions to rename that directory.

One common reason for the fact that it sometimes works and sometimes does not is that the program creates some of the directories it needs to rename but not others.

  • The directories created directly by the program have modify permissions for the user running the program, so it can rename those.
  • But, directories that were previously created by something else may restrict the access for the user running the program by default.

Read about Windows File and Folder permissions: http://technet.microsoft.com/en-us/library/bb727008.aspx

This will also fail if the host names are not "network qualified" the same way.

>>> os.renames(r'\\host.domain.com\joan\rocks', r'\\host\joan\jett\rocks')
WindowsError: [Error 5] Access is denied

>>> os.renames(r'\\host\joan\rocks', r'\\host\joan\jett\rocks')
>>>

>>> os.renames(r'\\host.domain.com\joan\rocks', r'\\host.domain.com\joan\jett\rocks')
>>>

I had a similar problem on Windows 10: sometimes my python script could not rename a directory even though I could manually rename it without a problem.

I used Sysinternal's handle.exe tool to find that explorer.exe had a handle to a sub-directory of the directory I was trying to rename. It turns out explorer was adding this sub-directory to its "Quick Access" section which prevented my script from renaming the folder.

I wound up disabling the "Show frequently used folders in Quick access" option from Explorer -> View -> Options -> General -> Privacy.

So if you have any file, application or folder that is open in the directory you are trying to rename you'll get that error. You to close them so that windows removes them from the quick access list. This worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM