1

I want to copy move some files from my PC to my USB but, when I run it it says:

WindowsError: [Error 5] Access denied: 'F:\\'

How can I use admin rights in python to avoid this error. Also, here is the code:

import os
import shutil
from os import walk

ruta='C:\\'
final='F:\\'
for (path,ficheros,archivos) in walk(ruta):
    for i in archivos:
        shutil.copytree(ruta,final)
    for i in ficheros:
        shutil.copytree(ruta,final)
1
  • 5
    How are you running the code? Have you tried Right click -> Run as Administrator?
    – jonrsharpe
    Sep 4, 2015 at 14:10

2 Answers 2

0

Some points to note:

  1. shutil.copytree() will already do a recursive file copy. There is no need to use os.walk to get each individual file. The following would be all that was needed:

    shutil.copytree('C:\\', 'F:\\')

  2. Trying to copy the whole of your C: drive to a USB will probably fail at some point, as some of the files and folders will not be copyable. It would be better to pick certain folders.

  3. You will get an Access denied error if you try to target the root folder on your USB stick. Also you need to make sure the target directory does not exist. Try the following:

    shutil.copytree('C:\\', 'F:\\c_drive')

  4. Lastly, doing a full copy like this will probably take a long time, and there will be no feedback as to how fast it is progressing. Your idea to use os.walk would solve this by allowing you to just copy a file at a time but the code would need fixing.

0

The simplest solution is to just launch the Python process as administrator. Depending on how you start the script, there are different ways to do that. The simplest solution is to just start a console as administrator and then run the Python command from there.

If you want something to double-click, you could also create a shortcut and running it by selecting “Run as administrator” from the context menu (right click menu).

Otherwise, you could also make the script request elevated permissions in some not-so-simple way.

Not the answer you're looking for? Browse other questions tagged or ask your own question.