首页 > 移动平台 > 详细

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

时间:2021-05-11 21:51:42      阅读:32      评论:0      收藏:0      [点我收藏+]

一、背景介绍

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

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

下面是这俩文件夹,便于理解我们的任务:
技术分享图片

二、脚本

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()

至于里面的路径,试试就完事了。
下面是项目结构
技术分享图片

3、结果:

移动成功,一秒钟的事情。
技术分享图片

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

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

原文:https://www.cnblogs.com/darkerg/p/14757061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!