Reputation: 119
I have a piece of code here that copies a list of directories etc from a config file. It runs and copies the directories etc but it still errors each time it runs, can anyone help me to understand why the error pops up or is there a way I can surpress it
The error is the following:
Traceback (most recent call last):
File "copydir.py", line 22, in <module>
shutil.copytree(sourcefile, destfile)
File "/usr/local/lib/python2.7/shutil.py", line 174, in copytree
os.makedirs(dst)
File "/usr/local/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: '/export/home/craigdba/My_backups/2012-10-24/'
The Code is
#!/usr/local/bin/python
import shutil
import datetime
import os
today=datetime.date.today()
todaystr=today.isoformat()
confdir=os.getenv("my_config")
dropbox=os.getenv("dropbox")
conffile = ('services.conf')
conffilename=os.path.join(confdir, conffile)
sourcedir=(r'/export/home/craigdba/')
destdir=os.path.join(dropbox, "My_backups"+"/"+todaystr+"/")
#os.makedirs(destdir)
for file_name in open(conffilename):
sourcefile=os.path.join(sourcedir, file_name.strip())
destfile=os.path.join(destdir, file_name.strip())
shutil.copytree(sourcefile, destfile)
Thanks in advance
Upvotes: 0
Views: 129
Reputation: 63
An easy way to fix this would be to delete the destination directory and then you are replacing it with the new directory anyway.
First check if the directory exists, if it does not make one.
Upvotes: 0
Reputation: 319531
It seems like you have an empty line in your servicers.conf
, may be at the end of file?
You can filter those in your code by checking:
fname = file_name.strip()
if fname:
sourcefile = os.path.join(...)
...
Upvotes: 2
Reputation: 7264
I would suggest checking to see if your destination directory exists before attempting to create it:
if not os.path.exists(destdir):
os.makedirs(destdir)
Upvotes: 0