如果文件已经在另一个目录中,则使用python复制该文件

2024-09-30 05:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个目录和另一个目录中都有jpg文件。 我想将jpgs从目录“C:/from/”复制到目录“C:/to/”,但仅当图像文件存在于“from”文件夹和“to”文件夹或“to”文件夹的子目录中时。如果图像不在“收件人”文件夹/子文件夹中,则不应复制该图像

这是我试过的。 首先,我从“from”文件夹创建了两个列表,其中包含每个文件的完整目录,另一个仅包含文件名(代码如下)。你知道吗

import os
import shutil

fromDir = "C:/from/"
toDir = "C:/to/"
lstFolder = [] # create a empty list that will hold the full file path
lstFile = [] # create a empty list that will hold the file name only

for root, dirs, files in os.walk(fromDir):
    for file in files:
        if file.endswith(".jpg"):
        lstFolder.append(os.path.join(root, file))
        lstFile = [x.replace("C/from/","") for x in lstFolder]

这将给我一个类似lstFolder==[“C:”from的列表/奶牛.jpg“,”C:/从/绵羊.jpg“,”C:/从/鸡肉.jpg“]
和 lstFile==[“奶牛.jpg","绵羊.jpg","鸡肉.jpg“]

现在如果“to”目录只有奶牛.jpg“和”绵羊.jpg然后应该复制“from”目录中的新图像。你知道吗

现在我尝试在“to”文件夹中搜索lstFile中的jpg名称(下面的代码)。但现在我不知道下一步该怎么办,我被困了一整天。请帮忙。你知道吗

lstTo = [] # a list that will hold all the file names that is in lstFile
for root, dirnames, filenames in os.walk(toDir):
    for jpgFile in lstFile:
        for filename in fnmatch.filter(filenames, jpgFile)
            lstTo.append(os.path.join(root, filename))

这会给我一个列表/奶牛.jpg“,”C:/to/notbeef/绵羊.jpg“]不包含文件”鸡肉.jpg““

现在我尝试了下面的代码,但是没有结果

for item in lstFile:
    shutil.copy2((x for x in lstFolder if item in x ),(y for y in lst2 if item in y ))

谢谢


Tags: 文件toinfrom目录文件夹forthat

热门问题