我有一个代码,用于将所有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)
发布于 2017-07-16 23:38:28
使用移动的副本,它应该自动覆盖文件。
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)
删除单个文件,然后逐个移动它们。
发布于 2020-12-03 02:06:31
除了上面的代码之外,我将文件夹移动到已经存在的目录中,这种冲突将产生一个错误,因此我建议使用shutil.copytree()
。
shutil.copytree('path_to/start/folder', 'path_to/destination/folder', dirs_exist_ok=True)
dirs_exist_ok=True
必须允许覆盖文件,否则会出现错误。
https://stackoverflow.com/questions/45134102
复制相似问题