【Python脚本】---两个文件夹中文件名相同扩展名不同的文件移动---对照&参照

一、背景介绍

前几日,夜晚十一点半,女朋友找我,说有一个问题,是这样的:

  • 有两个文件夹,其中一个文件夹中的文件名称都是00001.xml而另外一个文件夹中的文件名称都是00001.jpg这种类型
  • 任务是,jpg所在的文件夹有2000多张,而xml后缀的文件有828个。需要在3000多张jpg中匹配和xml文件名相同的,移动出来。
  • 如果一张一张搞,指定睡不了觉了,咋办,上网搜,还真有Python实现,Python牛逼。

下面是这俩文件夹,便于理解我们的任务:
image

二、脚本

1、获取xml那个文件夹下所有的文件名并保存为txt文档

import os


def ListFilesToTxt(dir, file, wildcard, recursion):
    exts = wildcard.split(" ")
    files = os.listdir(dir)
    for name in files:
        fullname = os.path.join(dir, name)
        if (os.path.isdir(fullname) & recursion):
            ListFilesToTxt(fullname, file, wildcard, recursion)
        else:
            for ext in exts:
                if (name.endswith(ext)):
                    file.write(name[:-4]+"\n")
                    break


def Test():
    dir = r"C:\Users\darkerg\Desktop\Annotations"
    outfile = "binaries.txt"
    wildcard = ".txt .exe .dll .lib .xml"

    file = open(outfile, "w")
    if not file:
        print("cannot open the file %s for writing" % outfile)

    ListFilesToTxt(dir, file, wildcard, 1)

    file.close()


Test()

2、移动

import shutil

if __name__ == '__main__':
    file_object = open('C:/Users/darkerg/Desktop/Del/binaries.txt', 'rU')
    try:
        for line in file_object:
            # print(line)
            shutil.move('C:/Users/darkerg/Desktop/2560  x 1440 p cropped/'+line.rstrip('\n')+'.jpg', "C:/Users/darkerg/Desktop/aaa/bbb")
    finally:
        file_object.close()

至于里面的路径,试试就完事了。
下面是项目结构
image

3、结果:

移动成功,一秒钟的事情。
image

Python还是牛逼啊,得多学学Python的类库,让工作学习效率更高,比如这次试用的os 和 shutil。女朋友拍手叫好,直呼牛,继续学吧。

posted @ 2021-05-11 19:44  DarkerG  阅读(1126)  评论(0编辑  收藏  举报