Python删除某些文件扩展名 [英] Python Deleting Certain File Extensions

查看:141
本文介绍了Python删除某些文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python还是很陌生,但是我已经使这段代码可以工作了,实际上,可以按照它的意图进行操作.

I'm fairly new to Python, but I have gotten this code to work, and in fact, do what it's intended to do.

但是,我想知道是否有更有效的方法对此进行编码,也许可以提高处理速度.

However, I'm wondering if there is a more efficient way to code this, perhaps to enhance the processing speed.

 import os, glob


def scandirs(path):
    for currentFile in glob.glob( os.path.join(path, '*') ):
        if os.path.isdir(currentFile):
            print 'got a directory: ' + currentFile
            scandirs(currentFile)
        print "processing file: " + currentFile
        png = "png";
        jpg = "jpg";
        if currentFile.endswith(png) or currentFile.endswith(jpg):
            os.remove(currentFile)

scandirs('C:\Program Files (x86)\music\Songs')

目前,大约有8000个文件,处理每个文件并检查它是否确实以png或jpg结尾需要花费一些时间.

Right now, there are about 8000 files, and it takes quite some time to process every file and check if it indeed ends in png or jpg.

推荐答案

由于要遍历子目录,因此请使用 os.walk :

Since you are recursing through subdirectories, use os.walk:

import os

def scandirs(path):
    for root, dirs, files in os.walk(path):
        for currentFile in files:
            print "processing file: " + currentFile
            exts = ('.png', '.jpg')
            if currentFile.lower().endswith(exts):
                os.remove(os.path.join(root, currentFile))

这篇关于Python删除某些文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆