【问题标题】:Moving files into specific directory using python get error file already exist使用 python 将文件移动到特定目录获取错误文件已存在
【发布时间】:2019-11-23 08:07:05
【问题描述】:

当我运行我的代码时,我得到了同样的错误:

---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-54-8d584fc326c3> in <module>
     16         filesToMove = gen_find("B"+str(o)+"_*",src)
     17         for name in filesToMove:
---> 18             shutil.move(name, dst)
Error: Destination path 'Dataset/300_train/1\B1_1.jpg' already exists

谁能帮我在这里检查我的代码?:

请解释一下

import os
import shutil
import fnmatch

def gen_find(filepat,top):
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat):
            yield os.path.join(path,name)

ranges = list(range(1,51))
for o in ranges:
    if __name__ == '__main__':
        src = 'Dataset/300_train' # input
        dst = 'Dataset/300_train/'+str(o) # desired     location

        filesToMove = gen_find("B"+str(o)+"_*",src)
        for name in filesToMove:
            shutil.move(name, dst)

如果已经存在,我想跳过复制文件

【问题讨论】:

  • 好吧,您可能运行了几次代码,所以有些文件确实存在。如果您需要帮助,您必须告诉我们如果那里已经有文件该怎么办。是否应该跳过副本?新文件应该覆盖旧文件吗?程序是否应该保留两者但重命名它们?
  • 我想跳过

标签: python file


【解决方案1】:

正如您在评论中所指的那样,如果您想跳过已经存在的文件,使用try... except 块真的很简单。您需要替换这部分代码

for name in filesToMove:
    shutil.move(name, dst)

用这个:

for name in filesToMove:
    try:
        shutil.move(name, dst)
    except shutil.Error:
        pass

【讨论】:

  • except 子句很危险,会隐藏不相关的问题并使调试变得困难。建议你改用except OSError:
  • @martineau 你说得对,我编辑得更具体了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-29
相关资源
最近更新 更多