Python Shutil.copy如果我有一个重复的文件,它会复制到新的位置吗
我正在使用python中的Python Shutil.copy如果我有一个重复的文件,它会复制到新的位置吗,python,shutil,Python,Shutil,我正在使用python中的shutil.copy方法 我发现定义如下: def copyFile(src, dest): try: shutil.copy(src, dest) # eg. src and dest are the same file except shutil.Error as e: print('Error: %s' % e) # eg. source or destination doesn't exist
shutil.copy
方法
我发现定义如下:
def copyFile(src, dest):
try:
shutil.copy(src, dest)
# eg. src and dest are the same file
except shutil.Error as e:
print('Error: %s' % e)
# eg. source or destination doesn't exist
except IOError as e:
print('Error: %s' % e.strerror)
我正在循环中访问定义。循环基于每次更改的字符串。代码查看目录中的所有文件,如果在文件中看到字符串的一部分,则将其复制到新位置
我很肯定会有重复的文件。所以我想知道会发生什么
它们会被复制还是会失败?不会将文件复制到新位置,它会覆盖文件
将文件src复制到文件或目录dst。如果dst是一个目录,
在中创建(或覆盖)与src具有相同基名的文件
指定的目录。权限位被复制。src和dst是
以字符串形式给出的路径名
因此,您必须检查目标文件是否存在,并根据需要更改目标文件。例如,这就是您可以用来实现安全拷贝的方法:
def safe_copy(file_path, out_dir, dst = None):
"""Safely copy a file to the specified directory. If a file with the same name already
exists, the copied file name is altered to preserve both.
:param str file_path: Path to the file to copy.
:param str out_dir: Directory to copy the file into.
:param str dst: New name for the copied file. If None, use the name of the original
file.
"""
name = dst or os.path.basename(file_path)
if not os.path.exists(os.path.join(out_dir, name)):
shutil.copy(file_path, os.path.join(out_dir, name))
else:
base, extension = os.path.splitext(name)
i = 1
while os.path.exists(os.path.join(out_dir, '{}_{}{}'.format(base, i, extension))):
i += 1
shutil.copy(file_path, os.path.join(out_dir, '{}_{}{}'.format(base, i, extension)))
这里,在扩展名的正前方插入一个
“u编号”
,以生成唯一的目的地名称,以防重复。就像'foo_1.txt'
谢谢,我其实对同一个东西的很多版本不感兴趣。因此,我在exist中添加了一个声明,这似乎非常有效。。谢谢你的意见