Advertisement

python批量提取子文件夹下指定名称的文件

阅读量:

python批量提取子文件夹下指定名称的文件

最近在处理数据集时遇到了一个问题,在每个文件夹中提取出第10张图片并将其移动到指定的目标文件夹中显得非常繁琐。为了提高效率和减少重复性工作量,在此编写了一些自动化脚本以实现这一目标

目录
目录样式

要提取每个子文件夹下名称后缀为_10.jpg的文件到一个新的文件夹中。

代码

复制代码
    import os
    import re
    import xlwt
    
    # 递归复制文件夹内的文件
    def copyFiles(sourceDir, targetDir):
    for file in os.listdir(sourceDir):
        sourceDir1 = os.path.join(sourceDir, file)  # 路径名拼接
        targetDir1 = os.path.join(targetDir)
        for file in os.listdir(sourceDir1):
            sourceDir2 = os.path.join(sourceDir1, file)
            # 忽略某些特定的子文件夹
            if sourceDir2.find("视点") > 0:
                # 列出源目录文件和文件夹
                for file in os.listdir(sourceDir2):
                    # 拼接完整路径
                    if re.search('_10.jpg', file):
                        sourceFile = os.path.join(sourceDir2, file)
                        targetFile = os.path.join(targetDir1, file)
    
                        if os.path.isfile(sourceFile):
                            if not os.path.exists(targetDir1):
                                os.makedirs(targetDir1)
                            if not os.path.exists(targetFile) or (os.path.exists(targetFile) and (
                                    os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
                                open(targetFile, "wb").write(open(sourceFile, "rb").read())
    copyFiles("C:\ Users\ yaotong\ Desktop\ OFD_full_DB_labelled\ pic", "copy")

os.listdir()列出目录路径

语法:os.listdir(path),path:需要列出的目录路径
用法:

复制代码
    import os, sys
    
    # 打开文件
    path = "/pic"
    dirs = os.listdir( path )
    
    # 输出所有文件和文件夹
    for file in dirs:
       print file

os.path.join() 路径拼接函数

语法:os.path.join(path1,path2,path3,…)
用法:

复制代码
    path1 = pic
    path2 = 0001
    path = os.path.join(path1,path2)
    print(path)
    
    结果:pic\0001

find()函数

语法规则:string.find(‘str’)计算从字符串scan到特定子字符串str的位置;若未找到则返回-1

复制代码
    string = 'hello,world'
    print(string.find('ello'))
    
    结果: (1,4)

re.rearch()扫描字符串

语法:该函数用于在字符串中搜索模式。其中模式用于匹配目标内容。输入的目标文本被传递进去。用法:

复制代码
    import re
    if re.rearch('he','helloworld')
    	print(true)
    	
    结果:true

其他方法

filestest用于确定给定路径是否为文件
exists用于确认给定路径是否存在,并根据结果返回布尔值
makedirs用于生成指定路径

copyFiles包含两个必要的参数: sourceDir为指定的起始目录位置;targetDir为目标存储的位置

结果

创建一个新的空白文本文件,并以test.py为文件名保存其中的代码。使用快捷键Shift + 右键→然后在此处启动命令提示符窗口,并输入python test.py并按回车键执行

好了

全部评论 (0)

还没有任何评论哟~