3

I'm trying to copy files from my current directory to a newly created folder in my current directory. The folder name is the exact date and time the script runs using the time module. I'm trying to use the shutil module because that's what everyone seems to say is the best for copying files from one place to another, but I keep getting a permission error. I've pasted the code and the error below. Any suggestions? Thanks in advance.

import os
import time
from shutil import copyfile
oldir = os.getcwd()
print(oldir)
timestr = time.strftime("%Y%m%d-%H%M%S")
print('timestr: {}'.format(timestr))
newdir = os.path.join(oldir + "\\" + timestr)
print(newdir)
for filename in os.listdir(os.getcwd()):
 if filename.startswith("green"):
 print (filename)
 copyfile(oldir, newdir)

error:

Traceback (most recent call last):
 File "\\directory\directory\Testing1.py", line 16, in <module>
 copyfile(oldir, newdir)
 File "C:\Python36-32\lib\shutil.py", line 120, in copyfile
 with open(src, 'rb') as fsrc:
PermissionError: [Errno 13] Permission denied: '\\\\directory\\directory'
asked Aug 29, 2017 at 21:23
1
  • 2
    That's because instead of copying a file you try to copy the current directory itself into its subdirectory. Commented Aug 29, 2017 at 21:32

1 Answer 1

4

You need to first create the directory and then when you make the copy, use the entire path to both the start file and then end file

import os
import time
from shutil import copyfile
oldir = os.getcwd()
print(oldir)
timestr = time.strftime("%Y%m%d-%H%M%S")
print('timestr: {}'.format(timestr))
newdir = os.path.join(oldir + "\\" + timestr)
print(newdir)
if not os.path.exists(newdir):
 os.makedirs(newdir)
for filename in os.listdir(os.getcwd()):
 if filename.startswith("green"):
 print (filename)
 copyfile(oldir+"\\"+filename, newdir + "\\" + filename)
answered Aug 29, 2017 at 21:37
Sign up to request clarification or add additional context in comments.

1 Comment

As pointed out, you cannot copy without checking that the directory exists or you create it first @Matt

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.