让编程成为一种习惯!坚持到2017!(2016.01.07)(Python:复制目录树)

来源:互联网 发布:mysql 批量update语句 编辑:程序博客网 时间:2024/06/05 08:04

让编程成为一种习惯!坚持到2017!有奖监督,如果发现我那天没写,我送乾颐堂T恤!(如果发现我哪天没有写,第一个微博或者博客留言的朋友,我送乾颐堂T恤)

==================Python:复制目录树=====================

import os, sysmaxfileload = 1000000blksize = 1024 * 500def copyfile(pathFrom, pathTo, maxfileload=maxfileload):if os.path.getsize(pathFrom) <= maxfileload:bytesFrom = open(pathFrom, 'rb').read()open(pathTo, 'wb').write(bytesFrom)else:fileFrom = open(pathFrom, 'rb')fileTo = open(pathTo, 'wb')while True:bytesFrom = fileFrom.read(blksize)if not bytesFrom: breakfileTo.write(bytesFrom)def copytree(dirFrom, dirTo, verbose = 2):fcount = dcount = 0for filename in os.listdir(dirFrom):pathFrom = os.path.join(dirFrom, filename)pathTo = os.path.join(dirTo, filename)if not os.path.isdir(pathFrom):try:if verbose > 1: print('copying', pathFrom, 'to', pathTo)copyfile(pathFrom, pathTo)fcount += 1except:print('Error copying', pathFrom, 'to', pathTo, '--skipped')print(sys.exc_info()[0], sys.exc_info()[1])else:if verbose: print('copying dir', pathFrom, 'to', pathTo)try:os.mkdir(pathTo)below = copytree(pathFrom, pathTo)fcount += below[0]dcount += below[1]dcount += 1except:print('Error creating', pathTo, '--skipped')print(sys.exc_info()[0], sys.exc_info()[1])return (fcount, dcount)def getargs():try:dirFrom, dirTo = sys.argv[1:]except:print('Usage error: cpall.py dirFrom dirTo')else:if not os.path.isdir(dirFrom):print('Error: dirFrom is not a directory')elif not os.path.exists(dirTo):os.mkdir(dirTo)print('Note: dirTo was created')return (dirFrom, dirTo)else:print('Warning: dirTo already exists')if hasattr(os.path, 'samefile'):same = os.path.samefile(dirFrom, dirTo)else:same = os.path.abspath(dirFrom) == os.path.abspath(dirTo)if same:print('Error: dirFrom same as dirTo')else:return (dirFrom, dirTo)if __name__ == '__main__':import timedirstuple = getargs()if dirstuple:print('Copying...')start = time.clock()fcount, dcount = copytree(*dirstuple)print('Copyed', fcount, 'files', dcount, 'directorys', end = ' ')print('in', time.clock() - start, 'seconds')<span style="color:#6f3198;"></span>

========================================
下面是代码的共享链接:
http://yunpan.cn/cm6MKfB8bz3ez  访问密码 4687

0 0
原创粉丝点击