Matt
Matt

Reputation: 1119

Copy Files Using Python

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'

Upvotes: 3

Views: 8592

Answers (1)

Bigbob556677
Bigbob556677

Reputation: 2158

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)

Upvotes: 4

Related Questions