![](/img/trans.png)
[英]How to prevent shutil.move from overwriting a file if it already exists?
[英]shutil.move if directory already exists
我有一个代码,用于将所有 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)
使用 copy insted of move,它应该会自动覆盖文件
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
才能允许覆盖文件,否则会出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.