Python 复制目录下的文件以及文件夹
使用windows的文件夹复制,发现经常在复制一部分文件后,因某些莫名其妙的原因被中断(提示某个文件复制失败,网络被断开,可能是由于网络不稳定),然后就要从头再来,搞了几个小时还没有搞完,烦死: }! |$ b# J5 k
就想到用python写个脚本来做这个事情:文件已经存在并且大小一致时不重复复制加快处理速度 8 k/ n0 Q) x! L; ]2 n
, g; {, c) e; @# {
代码如下
$ F+ y# t& u& a, T" [+ \2 O
Python代码 7 k& w6 l/ S% |7 L+ S
1.#! /usr/bin/env python
2.# -*- coding: utf-8 -*-
3.#@author zcwang3@gmail.com
4.#@version 2010-09-25 14:57
5.) C" z1 R$ e. V3 O
6.import os 6 h' X5 q# }3 R) D
7.import time
8.) n- m# Y6 Y4 {. R$ B
9.sourceDir = r"\\192.168.3.250\mmtimages"* U: o# C, q. ?( P$ C; N
10.targetDir = r"D:\mmtimages"
11.copyFileCounts = 05 N; A" p& e8 j/ X
12.
13.def copyFiles(sourceDir, targetDir):
14. global copyFileCounts 2 F$ ?0 S7 u' D: ?8 t+ t8 P
15. print sourceDir 8 g$ j4 F1 Y; U
16. print u"%s 当前处理文件夹%s已处理%s 个文件" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), sourceDir,copyFileCounts)
17. for f in os.listdir(sourceDir): $ E7 f, c; m3 lN# V1 T+ c
18. sourceF = os.path.join(sourceDir, f) 3 x2 Q, S! n& [9 c: z6 u
19. targetF = os.path.join(targetDir, f) * ]1 |A! W) I- J$ C: DL
20. " @9 O: F# U# {- W% G4 h* M; u
21. if os.path.isfile(sourceF):
22. #创建目录
23. if not os.path.exists(targetDir): 6 o1 i5 G! n% n% S8 i7 }7 @" t
24. os.makedirs(targetDir) 2 v. d+ Y5 r) e! W- t
25. copyFileCounts += 16 t; S* b8 X$ A! m
26.
27. #文件不存在,或者存在但是大小不同,覆盖
28. if not os.path.exists(targetF) or (os.path.exists(targetF) and (os.path.getsize(targetF) != os.path.getsize(sourceF))): 7 Z6 X$ Z3 K0 W' M
29. #2进制文件 * l$ _o- b2 ~" a
30. open(targetF, "wb").write(open(sourceF, "rb").read()) ; V* `( G! i+ w& |* Cn
31. print u"%s %s 复制完毕" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF)
32. else: # ~# k1 b! N) [% u
33. print u"%s %s 已存在,不重复复制" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF) / H) h# ~! K8 G6 ?; m+ t, F; y
34.
35. if os.path.isdir(sourceF):
36. copyFiles(sourceF, targetF)
37. 3 v# W1 c/ ~% @9 D! {
38.if __name__ == "__main__": 5 r) t2 X+ A2 ^5 na, E
39. try:
40. import psyco + Q5 l* N# I) b! D3 ^# m1 X! j( u
41. psyco.profile()
42. except ImportError: 0 [. e+ N0 ]. |* B
43. pass& t; o) v& K9 U& y
44. copyFiles(sourceDir,targetDir)
页:
[1]