Python递归目录并统计指定后缀文件个数/批量重命名/批量复制文件

递归某目录下所有文件,以及打印出这些文件的上一级目录,文件名和后缀名等.

import os

def recur_files(path):
    pcd_lst = []
    label_lst = []
    parents = os.listdir(path)
    for parent in parents:
        child = os.path.join(path,parent)
        if os.path.isdir(child):
            recur_files(child)
        else:
            print(os.path.dirname(child))#parent folder
            basename, ext = os.path.splitext(os.path.basename(child))
            print(basename)#filename
            print(ext)#extention,include'.'

加上统计某一后缀文件个数功能:

import os

count = 0

def recur_files(path):
    global count
    parents = os.listdir(path)
    for parent in parents:
        child = os.path.join(path,parent)
        if os.path.isdir(child):
            recur_files(child)
        else:
            basename, ext = os.path.splitext(os.path.basename(child))

            if ext == '.pcd':
                count += 1

    return count

import os


pcd_lst = []
label_lst = []
def recur_files(path):
    for root, _, files in os.walk(path):
        for file in files:
            if file.endswith(".pcd"):
                pcd_lst.append(os.path.join(root, file))


if __name__ == '__main__':
    my_dir = os.getcwd()
    recur_files(my_dir)
    label_lst = [p.replace('pcds', 'labels') for p in pcd_lst]
    label_lst = [l.replace('.pcd', '.json') for l in label_lst]
    assert(len(pcd_lst) == len(label_lst))
    length = len(pcd_lst)
    with open(os.path.join('train_list.txt'),'wb') as fin:
        for i in range(length):
            fin.write(pcd_lst[i] + " " + label_lst[i]  + "\n")

再来个批量重命名文件:

import os

def recur_files(path):
    global count
    parents = os.listdir(path)
    for parent in parents:
        child = os.path.join(path,parent)
        if os.path.isdir(child):
            recur_files(child)
        else:
            basename, ext = os.path.splitext(os.path.basename(child))
            if ext == '.mp3':
                os.rename(basename+ext,basename.replace(' [mqms]','') +ext)
                #count += 1

if __name__ == '__main__':
    recur_files(os.getcwd())

批量复制文件到某一盘符/文件夹:

import shutil

count = 0
def recur_files(path):
    global count
    parents = os.listdir(path)
    for parent in parents:
        child = os.path.join(path,parent)
        if os.path.isdir(child):
            recur_files(child)
        else:
            basename, ext = os.path.splitext(os.path.basename(child))
            if ext == '.mp3':
                count += 1
                #print(os.path.dirname(child)+ "\\" + basename+ext)
                shutil.copy(os.path.dirname(child)+ "\\" + basename+ext, r"G:")
              

                #count += 1

if __name__ == '__main__':
    recur_files(os.getcwd())
    

参考:震惊!Python竟然是这样的修改全局变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值