use*_*916 36 shutil python-2.7
以下是将移动和替换单个文件的代码
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)
Run Code Online (Sandbox Code Playgroud)
如果我执行相同的命令并移动已经存在的文件dst folder
我正在获取shutil.Error: Destination path './dstFolder/file.txt' already exists
如何移动并替换相同的文件名已经存在
eca*_*mur 74
如果指定目标的完整路径(而不仅仅是目录),shutil.move
则会覆盖任何现有文件:
shutil.move(os.path.join(src, filename), os.path.join(dst, filename))
Run Code Online (Sandbox Code Playgroud)
小智 5
我通过在移动命令中为源和目标提供完整路径来覆盖它......记得为 Windows 路径添加双斜杠。
# this is to change directories (type your own)
os.chdir("C:\REPORTS\DAILY_REPORTS")
# current dir (to verify)
cwd = os.getcwd()
src = cwd
dst = cwd + '\\XLS_BACKUP\\'
shutil.move(os.path.join(src, file), os.path.join(dst, file))
# nice and short.
Run Code Online (Sandbox Code Playgroud)