Python Shutil.copy if i have a duplicate file will it copy to new location -


i have working shutil.copy method in python

i found definition listed below

def copyfile(src, dest):     try:         shutil.copy(src, dest)     # eg. src , dest same file     except shutil.error e:         print('error: %s' % e)     # eg. source or destination doesn't exist     except ioerror e:          print('error: %s' % e.strerror) 

i accessing defination inside loop. loop based on string changes each time.the code looks @ files in directory , if see part of string in file copies new location

i pretty sure there duplicate files. wondering happen. copy , fail

shutil.copy not copy file new location, overwrite file.

copy file src file or directory dst. if dst directory, a file same basename src created (or overwritten) in directory specified. permission bits copied. src , dst path names given strings.

so have check if destination file exists , alter destination appropriate. example, can use achieve safe copy:

def safe_copy(file_path, out_dir, dst = none):     """safely copy file specified directory. if file same name      exists, copied file name altered preserve both.      :param str file_path: path file copy.     :param str out_dir: directory copy file into.     :param str dst: new name copied file. if none, use name of original         file.     """     name = dst or op.basename(file_path)     if not op.exists(op.join(out_dir, name)):         shutil.copy(file_path, op.join(out_dir, name))     else:         base, extension = op.splitext(name)         = 1         while op.exists(op.join(out_dir, '{}_{}{}'.format(base, i, extension))):             += 1         shutil.copy(file_path, op.join(out_dir, '{}_{}{}'.format(base, i, extension))) 

here, '_number' inserted right before extension generate unique destination name in case of duplicate. 'foo_1.txt'.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -