python 实现文件的递归拷贝-转

 1 # -*- coding: utf-8 -*-
 2 #!/usr/bin/python
 3 #Filename:copyfile.py
 4 import os,shutil
 5 def mycopy(srcpath,dstpath):
 6     if not os.path.exists(srcpath):
 7         print "srcpath not exist!"
 8     if not os.path.exists(dstpath):
 9         print "dstpath not exist!"
10     for root,dirs,files in os.walk(srcpath,True):
11         for eachfile in files:
12             shutil.copy(os.path.join(root,eachfile),dstpath)
13 srcpath='e:\\pic'
14 dstpath='f:\\pictotal'
15 mycopy(srcpath,dstpath)

代码没有什么难懂的,主要是os.walk()函数,这个函数返回指定路径的三元组(起始路径,起始路径下的目录,起始路径下不带路径名的文件名列表)

它直接可以递归遍历到指定目录下的所有目录及文件名,比较好用。

也可以用os.listdir(dirname):函数来实现,listdir函数列出dirname下的目录和文件,然后通过一个判断:若是文件,则拷贝;若是目录,则继续递归

遍历,显然没有walk()函数用起来方便。不过不知道walk()函数内部是怎么实现的,若是直接将根目录下的所有文件存在list中性能上可能不太好,

后面可以用listdir()对比测一下。

 

可以看出,python仅需短短几行的代码就完成了这个工作,还是很方便的。

posted @ 2013-06-09 10:13  曾先森在努力  阅读(410)  评论(0)    收藏  举报