python中的glob、shutil、rmtree、remoevall

最近在处理数据的时候需要把所有的文件copy成一个,需要实现类似dos下面的copy *.* a.dat,copy结束后,将a.dat 移动到另一个文件夹,同时清空文件。中间试了下shutil,结果发现在rmtree时候经常出错,总有一个文件删除不了。查了半天不清楚原因所在,后来刚好找到了个写好了错误处理的代码,直接使用了。这里glob很好用,可以获取一个当前目录下的文件列表,而且可以给定文件通配符。

    ff=glob.glob("*.ABJ")
    fout = file('fn.dat', 'wb')
    for n in ff:
        fin = file(n, 'rb')
        shutil.copyfileobj(fin, fout, 65536)
        fin.close()
    fout.close()
    fn=datadir+"fn.dat"
    shutil.move(fn,exedir)
    #raw_input("Press ENTER to exit")
    os.chdir("..")
    print os.getcwd()
    #shutil.rmtree(datadir)
    removeall.removeall(datadir)
    print "ok"  

 其中for循环中指定 了65536为防止文件太大。

shutil.rmtree本身没有进行错误处理,本来准备自己写,刚好发现一个别人写好的代码,直接拿来用了。

#! /usr/bin/env python
#coding=utf-8
## {{{ Recipe 193736 (r1): Clean up a directory tree 
""" removeall.py:

   Clean up a directory tree from root.
   The directory need not be empty.
   The starting directory is not deleted.
   Written by: Anand B Pillai <abpillai@lycos.com> """

import sys, os

ERROR_STR= """Error removing %(path)s, %(error)s """

def rmgeneric(path, __func__):

    try:
        __func__(path)
        print 'Removed ', path
    except OSError, (errno, strerror):
        print ERROR_STR % {'path' : path, 'error': strerror }
            
def removeall(path):

    if not os.path.isdir(path):
        return
    
    files=os.listdir(path)

    for x in files:
        fullpath=os.path.join(path, x)
        if os.path.isfile(fullpath):
            f=os.remove
            rmgeneric(fullpath, f)
        elif os.path.isdir(fullpath):
            removeall(fullpath)
            f=os.rmdir
            rmgeneric(fullpath, f)
## End of recipe 193736 }}}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值