Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 763
Matt Avatar asked May 25 '26 06:05

Matt


1 Answers

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)
like image 145
Bigbob556677 Avatar answered May 26 '26 20:05

Bigbob556677



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!