Quinton Ships Quinton Ships - 1 year ago 274
Python Question

Python - Errno 13 Permission denied when trying to copy files

I am attempting to make a program in Python that copies the files on my flash drive (letter D:) to a folder on my hard drive but am getting a PermissionError: [Errno 13] Permission denied: 'D:'.

The problematic part of my code is as follows:

# Copy files to folder in current directory
def copy():
source = getsource()

if source != "failure":

copyfile(source, createfolder())
wait("Successfully backup up drive"
"\nPress 'Enter' to exit the program")

wait("No USB drive was detected"
"\nPress 'Enter' to exit")

# Create a folder in current directory w/ date and time
def createfolder():
name = strftime("%a, %b %d, %Y, %H.%M.%S", gmtime())
dir_path = os.path.dirname(os.path.realpath(__file__))
new_folder = dir_path + "\\" + name

return new_folder

Everything seems to run fine until the copyfile() function runs, where it returns the error.
I tried replacing getsource() with the destination of the file instead and it returned the same permission error except for the new_folder directory instead.

I have read several other posts but none of them seem to be relevant to my case. I have full admin permissions to both locations as well.
Any help would be greatly appreciated!

Answer Source

As I stated in my comment above, it seems as if you're trying to open the directory, D:, as if it was a file, and that's not going to work because it's not a file, it's a directory.

What you can do is use os.listdir() to list all of the files within your desired directory, and then use shutil.copy() to copy the files as you please.

Here is the documentation for each of those:

os.listdir() (You will be passing the full file path to this function)

shutil.copy() (You will be passing each file to this function)

Essentially you would store all of the files in the directory in a variable, such as all_the_files = os.listdir(/path/to/file), then loop through all_the_files by doing something like for each_file in all_the_files: and then use shutil.copy() to copy them as you please.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download