import os
import shutil
import re
class CollectFile:
def __init__(self, source, dest, types, explict=None):
self.source = source
self.types = tuple(types)
self.dest = dest
self.explict = tuple(explict)
self.explict = '|'.join(explict)
def _move(self, arg, dirname, fnames):
if re.search(self.explict, dirname):
return
for fname in fnames:
if fname.endswith(self.types):
src = dirname+'\\'+fname
shutil.move(src, self.dest)
def _copy(self, arg, dirname, fnames):
if re.search(self.explict, dirname):
return
for fname in fnames:
if fname.endswith(self.types):
src = dirname+'\\'+fname
shutil.copy(src, self.dest)
def run(self, method):
if method == 'move':
os.path.walk(self.source, self._move, None)
elif method == 'copy':
os.path.walk(self.source, self._copy, None)
else:
raise TypeError('function --run-- parameter wrong')
if __name__ == '__main__':
print '''
Collect File program
Author:p1usj4de
Notice:Mutiple input split with blank
'''
source_dir = raw_input('source dir(default d:\\):')
dest_dir = raw_input('dest dir(default source dir):')
method = raw_input('you want to \'move\' or \'copy\'(default move)?')
types = raw_input('types (default movies):')
explict_dirs = raw_input('explict dirs(default movie,media and lin):')
if source_dir == '':
source_dir = 'd:\\'
if types != '':
types = types.split(' ')
else:
types = ('mp4', 'avi', 'rmvb', 'wmv')
if dest_dir == '':
dest_dir = source_dir
if explict_dirs == '':
explict_dirs = ('movie','media','lin')
else:
explict_dirs = explict_dirs.split(' ')
if method == '':
method = 'move'
cf = CollectFile(source_dir, dest_dir, types=types, explict=explict_dirs)
cf.run(method)
没啥难点的,主要就是调用os.path.walk和shutil模块。其中值得注意的就是shutil.copyfile的dest必须是文件名,而copy的dest可以是文件夹。另外在自定义的文件遍历函数中,def _move(self, arg, dirname, fnames)中dirname是不带最后的斜杠的,也就是说要表达source的话必须写成,dirname+'\\'+fname。