【发布时间】:2021-03-16 18:46:45
【问题描述】:
我正在尝试弄清楚如何检查源文件夹中的文件是否存在于目标文件夹中,然后将文件复制到目标文件夹。
如果源文件夹中的文件存在于目标文件夹中,请将源文件夹中的文件重命名为“_1”或_i+1,然后将其复制到目标文件夹。
例如(不会是.txt,仅以此为例,文件本质上是动态的):
我想将 file.txt 从文件夹 a 复制到文件夹 b。
file.txt 已存在于文件夹 b a 中。如果我尝试将 file.txt 复制到文件夹 b,我会收到复制错误。
将 file.txt 重命名为 file_1.txt将 file_1.txt 复制到文件夹 b b。如果 file_1.txt 存在,则将其设为 file_2.txt
到目前为止,我所拥有的是:
for filename in files:
filename_only = os.path.basename(filename)
src = path + "\\" + filename
failed_f = pathx + "\\Failed\\" + filename
# This is where I am lost, I am not sure how to declare the i and add _i + 1 into the code.
if path.exists(file_path):
numb = 1
while True:
new_path = "{0}_{2}{1}".format(*path.splitext(file_path) + (numb,))
if path.exists(new_path):
numb += 1
shutil.copy(src, new_path)
else:
shutil.copy(src, new_path)
shutil.copy(src, file_path)
非常感谢。
【问题讨论】:
标签: python python-3.x copy file-rename shutil