我有一个代码,用于将所有 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
这是我的代码
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")
我可以做些什么来覆盖文件或检查文件是否存在并跳过它?
我能够按照@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)
使用复制代替移动,它应该会自动覆盖文件
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)
然后将它们一一移动
除了上面的代码之外,我还将文件夹移动到已经存在的目录中,这种碰撞会产生错误,所以我建议
shutil.copytree()
shutil.copytree('path_to/start/folder', 'path_to/destination/folder', dirs_exist_ok=True)
需要
dirs_exist_ok=True
才能允许覆盖文件,否则会出现错误。
实际上,我认为不应该使用任何shutil方法来完成此任务只要两个路径位于同一设备上,但是https://docs.python.org/3/library/pathlib。 html#pathlib.Path.replace
这应该更像预期的
mv
un*x 系统命令:只需移动文件系统句柄(ext3 中的 inode),而不是内容本身并无条件覆盖文件。