我有一个用于将所有jpg文件从源移动到目标的代码。第一次代码运行正常,它移动了文件,但是如果我再次运行它,则会出现一个错误,表明该文件已存在。
Traceback (most recent call last):
File "/Users/tom/Downloads/direc.py", line 16, in <module>
shutil.move(jpg, dst_pics)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 542, in move
raise Error("Destination path '%s' already exists" % real_dst)
shutil.Error: Destination path '/Users/tom/Downloads/Dest/Pictures/Photo3.jpg' already exists
Run Code Online (Sandbox Code Playgroud)
这是我的代码
import os
import glob
import shutil
local_src = '/Users/tom/Downloads/'
destination = 'Dest'
src = local_src + destination
dst_pics = src + '/Pictures/'
print(dst_pics)
for pic in glob.iglob(os.path.join(src, "*.jpg")):
if os.path.isfile(pic):
if not (os.path.isfile(dst_pics + pic)):
shutil.move(pic, dst_pics)
else:
print("File exists")
Run Code Online (Sandbox Code Playgroud)
我有什么办法可以覆盖文件或检查文件是否存在并跳过它?
我能够通过遵循@Justas G解决方案来解决。
这是解决方案
for pic in glob.iglob(os.path.join(src, "*.jpg")):
if os.path.isfile(pic):
shutil.copy2(pic, dst_pics)
os.remove(pic)
Run Code Online (Sandbox Code Playgroud)
除了上面的代码之外,我还将文件夹移动到已经存在的目录中,这种冲突会产生错误,所以我建议shutil.copytree()
shutil.copytree('path_to/start/folder', 'path_to/destination/folder', dirs_exist_ok=True)
Run Code Online (Sandbox Code Playgroud)
需要dirs_exist_ok=True允许覆盖文件,否则会出现错误。
使用移动的副本插入,它将自动覆盖文件
shutil.copy(sourcePath, destinationPath)
然后,当然您需要删除原始文件。请注意,shutil.copy不会复制或创建目录,因此您需要确保它们存在。
如果这也不起作用,则可以手动检查文件是否存在,将其删除并移动新文件:
要检查文件是否存在,请使用:
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.exists(): 检查路径是否存在
if my_file.is_dir(): 检查目录是否存在
if my_file.is_file(): 检查文件是否存在
要删除目录及其所有内容,请使用:
shutil.rmtree(path)
或使用删除单个文件,
os.remove(path)然后一个一个地移动它们