16 Star 45 Fork 46

现任明教教主-乾颐堂/qytang_Python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
2016.1.7复制目录树 2.13 KB
一键复制 编辑 原始数据 按行查看 历史
import os, sys
maxfileload = 1000000
blksize = 1024 * 500
def 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: break
fileTo.write(bytesFrom)
def copytree(dirFrom, dirTo, verbose = 2):
fcount = dcount = 0
for 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 += 1
except:
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 += 1
except:
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 time
dirstuple = 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')
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/qytang/qytang_Python.git
git@gitee.com:qytang/qytang_Python.git
qytang
qytang_Python
qytang_Python
master

搜索帮助