如果相同的文件名已存在,则移动和替换? [英] Move and replace if same file name already exists?

查看:108
本文介绍了如果相同的文件名已存在,则移动和替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是移动和替换单个文件的代码:

Here is below code which will move and replace individual file:

import shutil
import os
src = 'scrFolder'
dst = './dstFolder/'
filelist = []

files = os.listdir( src )
for filename in files:
    filelist.append(filename)
    fullpath = src + '/' + filename
    shutil.move(fullpath, dst)

如果我执行相同的命令并移动 dst 文件夹 中已经存在的文件,我会收到 shutil.Error: Destination path './dstFolder/file.txt' already exists.如果相同的文件名已存在,如何移动和替换?

If I execute same command and moving file which already existed in dst folder, I am getting shutil.Error: Destination path './dstFolder/file.txt' already exists. How to do move and replace if same file name already exists?

推荐答案

如果您指定目标的完整路径(不仅仅是目录),则 shutil.move 将覆盖任何现有文件:

If you specify the full path to the destination (not just the directory) then shutil.move will overwrite any existing file:

shutil.move(os.path.join(src, filename), os.path.join(dst, filename))

这篇关于如果相同的文件名已存在,则移动和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆