xiagu1 发表于 2013-1-28 19:03:01

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, osERROR_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 }}}
页: [1]
查看完整版本: python中的glob、shutil、rmtree、remoevall