例子

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

代码如下 复制代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import shutil
dir = "/mnt/Packages"
class Packages:
    def __init__(self,srcdir,desdir):
        self.sdir=srcdir
        self.ddir=desdir
    def check(self):
        print('program start...')
        for dirpath

, dirnames, filenames in os.walk(self.sdir):  www.111cn.Net  #遍历文件
            for filename in filenames:
                thefile=os.path.join(dirpath,filename)            #文件的绝对地址
                try:
                    if os.path.splitext(thefile)[1]=='.rpm':      #筛选.rpm格式的文件
                        #print('Fount rpm package: ' + thefile)
                        if 'inspuer' in os.popen('rpm -qpi ' + thefile).read().rstrip():
                            print('Found error package: ' + thefile)
                            shutil.copy(thefile, self.ddir)  #将错误文件复制到desdir目录
                            f = open('list.txt', 'a')    #将错误文件列表写入到list.txt
                            f.write(filename + ' ')
                            f.close()
                except IOError, err:
                    print err
                    sys.exit()
 
if __name__ == '__main__':
    dir=Packages('/mnt/cdrom','/mnt/erpm')   #源目录为/mnt/cdrom,目标目录为/mnt/erpm
    dir.check()

例子,遍历目录下文件

代码如下 复制代码

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)

更多详细内容请查看:http://www.111cn.net/phper/python/58530.htm

python遍历目录文件脚本的示例的更多相关文章

  1. Python遍历目录下所有文件的最后一行进行判断若错误及时邮件报警-案例

    遍历目录下所有文件的最后一行进行判断若错误及时邮件报警-案例: #-*- encoding: utf-8 -*- __author__ = 'liudong' import linecache,sys ...

  2. Python 遍历目录下的子目录和文件

    import os A: 遍历目录下的子目录和文件 for root,dirs ,files in os.walk(path) root:要访问的路径名 dirs:遍历目录下的子目录 files:遍历 ...

  3. 用Python遍历目录

    用Python遍历指定目录下的文件,一般有两种常用方法,但它们都是基于Python的os模块.下面两种方法基于Python2.7,主要用到的函数如下: 1.os.listdir(path):列出目录下 ...

  4. python遍历目录os.walk(''d:\\test2",topdown=False)

    os.walk(top, topdown=True, onerror=None, followlinks=False)遍历目录,topdown=false表示先返回目录,后返回文件 参数说明: top ...

  5. c#调用api(FindFirstFile,FindNextFile)高效遍历目录文件【转载】

    在c#下遍历目录,应用最多的应该就是 System.IO.DirectoryInfo.GetDirectories或GetFiles了,但是当目录特别大,文件特别多时,效率不尽人意,此时我们很容易想到 ...

  6. python模块目录文件后续

    1,新增PythonModule加载path Ruiy tip(关于python list[]数据库类型特殊你懂的!append(""),extend([""] ...

  7. ZH奶酪:PHP遍历目录/文件的3种方法

    其实PHP中内建函数scandir()就可以返回目录下全部文件和目录了... ========================== 1.使用$obj = dir($dir)返回目录对象$obj,然后使 ...

  8. Python遍历一个文件夹下有几个Excel文件及每个Excel文件有几个Sheet

    一. 解决问题: 工作中常会遇到合并Excel文件的需求,Excel文件数量不确定,里面的Sheet 数量是可变的,Sheet Name是可变的,所以,需要用到遍历一个文件夹下有几个Excel文件,判 ...

  9. linux 遍历目录+文件(优化版本)

    c++17 filesystem, regex 遍历目录 #include <stdio.h> #include <sys/types.h> #include <dire ...

随机推荐

  1. Laravel入门笔记

    Laravel 是一款简洁,优雅的一款框架,可以说是入门TP后的第二款可以选择的框架. 目录部分: app -> 自己写的代码 http -> Controller -> 控制器 b ...

  2. C# 解压zip压缩文件

    此方法需要在程序内引用ICSharpCode.SharpZipLib.dll 类库 /// <summary> /// 功能:解压zip格式的文件. /// </summary> ...

  3. Android下结束进程的方法

    转自:http://www.cnblogs.com/crazypebble/archive/2011/04/05/2006213.html 最近在做一个类似与任务管理器的东西,里面有个功能,可以通过这 ...

  4. ubuntu 15.04开放mysql远程连接

    首先查看端口是否打开 netstat -an|grep 3306 此图为开启3306端口的截图,之前显示为. . . 127.0.0.1:3306 . . . 打开mysql配置文件vi /etc/m ...

  5. PP常用T-CODE

    与BOM相关 CS00 BOM 菜单 BOM Menu CS01 生成物料 BOM Create Material BOM CS02 更改物料 BOM Change Material CS03 显示物 ...

  6. Codeforces Testing Round #12 A. Divisibility 水题

    A. Divisibility Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/597/probl ...

  7. Android编译提示ImportError: No module named bz2的解决办法

    在安装node.js时提示ImportError: No module named bz2.很明显这个python中没有装bz2的库导致的.解决方法:sudo apt-get install libb ...

  8. iOS开发——图形编程OC篇&OpenGL ES2.0编程步骤

    OpenGL ES2.0编程步骤 OpenGL ES (OpenGL for Embedded Systems) 是 OpenGL 三维图形 API 的子集,针对手机.PDA和游戏主机等嵌入式设备而设 ...

  9. Cordova 3.0 + Eclipse 开发流程

    cd d:\cordova\projectscordova create HelloWorld com.example.helloworld HelloWorldcd HelloWorldcordov ...

  10. google maps api申请的问题

    现在已经改由统一的GOOGLE API控制台进行所有GOOGLE API的管理了. 方法是使用Google帐号登入 https://code.google.com/apis/console. 然后在所 ...