Python使用shutil.move移动文件报目标路径已存在错误如何解决
问题根因
你的代码存在两处核心逻辑错误:
- 缩进错误:文件判断、移动的代码完全写在
for循环外部,循环仅执行了拼接路径、打印目标路径的逻辑,循环结束后变量s仅保留了文件列表最后一个元素的源路径,只会对最后一个文件做处理,不可能输出3条exist。 - 判断逻辑错误:
if s in source是判断完整源文件路径字符串是否为源目录字符串的子串,这个判断永远成立,完全无法实现「判断文件是否需要移动」的效果。你要判断的是源路径下的对应文件是否真实存在,或目标路径下是否已经存在同名文件,避免重复移动报错。
修复后的实现代码
import os import shutil source = '/home/jupyter/.fastai/data/mnist_sample/valid/3/' destination = '/home/jupyter/.fastai/data/mnist_sample/train/3/' files_to_move = ['50560.png', '57306.png', '983.png'] for file in files_to_move: # 用os.path.join拼接路径更稳妥,避免手动拼接的斜杠兼容问题 s = os.path.join(source, file) d = os.path.join(destination, file) # 源文件存在、且目标文件不存在时才执行移动 if os.path.exists(s) and not os.path.exists(d): print("File is moving") shutil.move(s, destination) print('Moved:', file) else: print("exist")
修改后首次运行会移动三个存在的源文件,打印对应移动日志;再次运行时三个文件已经不在源路径、或目标路径已存在对应文件,就会输出3条exist,不会抛出报错。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

