首页 > 解决方案 > Python:删除/复制文件。第一次运行成功,现在没有

问题描述

我的 python 脚本有问题。我的项目:我有两个带有图片的文件夹。源是所有未排序的图片,目标是在文件夹中排序的相同图片(以及更多)。目标文件夹中的某些文件已损坏,因此我创建了一个脚本,用源文件夹中的相同图片替换目标(以及正确路径)中的所有图片。为了测试,我选择了一个文件夹。我运行了脚本,一切正常。我添加了一些打印并再次启动脚本(相同的测试文件夹),现在它什么也不做。

dirTarget = "C:\\Users\\jh\\Documents\\_BACKUP\\09-2020"
dictTarget = {}

dirSource = "D:\\AllPictures"

for root, dirs, files in os.walk(dirSource):
    for file in files:
        iSource += 1
        fName, fExtention = os.path.splitext(file)
        #tmpFile = root + "\\" + fName + fExtention
        tmpFile = os.path.join(root, file)
        
        dictSource.update({file : tmpFile})
        #print(tmpFile)
        
for root, dirs, files in os.walk(dirTarget):
    for file in files:
        iTarget += 1
        fName, fExtention = os.path.splitext(file)
        targetFile = os.path.join(root, file)
        
        dictTarget.update({file : targetFile})
        
        if fName.lower().startswith("img_"):
            iScope += 1
            replaceWith = dictSource.get(file)
            if replaceWith == None:
                iNA += 1
                print(targetFile + "### Not found! ###")
            else:
                iReplace += 1
                
                try:
                    print("Copy %s ==> %s" %(replaceWith, targetFile))
                    os.remove(targetFile)
                    shutil.copy(replaceWith, targetFile)
                    iReplaced += 1
                except:
                    print("########## ERROR #################")

输出看起来不错。我也不例外,我的调试信息被打印出来,我的数字是正确的..但什么也没发生。如果我启动脚本,它几乎立即完成。在第一次运行中,完成这项工作需要一段时间。

我创建了一个新的测试文件夹,并再次尝试。相同的行为:第一次运行有效,第二次运行什么也没做..

任何想法可能是什么问题?有没有类似缓冲区的东西?我在 Windows、Eclipse 和 Python 3.9.2 上

提前致谢!

标签: pythonpython-3.xcopy

解决方案


推荐阅读