Python遍历目录文件脚本的示例

例子

自己写的一个Python遍历文件脚本,对查到的文件进行特定的处理。没啥技术含量,但是也记录一下吧。

代码如下 复制代码

例子,遍历目录下文件

代码如下 复制代码

def search(folder, filter, allfile):
    folders = os.listdir(folder)
    for name in folders:
        curname = os.path.join(folder, name)
        isfile = os.path.isfile(curname)
        if isfile:
            ext = os.path.splitext(curname)[1]
            count = filter.count(ext)
            if count>0:
                cur = myfile()
                cur.name = curname
                allfile.append(cur)
        else:
            search(curname, filter, allfile)
    return allfile

例子

遍历文件夹并删除特定格式文件

代码如下 复制代码

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import os
 
def del_files(path):
    for root , dirs, files in os.walk(path):
        for name in files:
            if name.endswith(".tmp"):
                os.remove(os.path.join(root, name))
  print ("Delete File: " + os.path.join(root, name))
 
# test
if __name__ == "__main__":
    path = '/tmp'
    del_files(path)

下面关于Python的文章您也可能喜欢,不妨看看:

Python 的详细介绍请点这里
Python 的下载地址请点这里 

猜你喜欢

转载自www.linuxidc.com/Linux/2015-12/126838.htm
今日推荐