• 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仅需短短几行的代码就完成了这个工作,还是很方便的。

  • 相关阅读:
    SpringMvc框架总结
    Spring框架总结
    Redis常用数据类型
    从配置文件中获取list,set,map值
    Oracle数据库编码格式不同造成乱码
    事务
    Spring-动态代理
    关于Maven项目pom.xml文件不报错却有红叉的问题
    Spring—SSJ集成&声明式事务管理
    Spring-构造注入&注解注入&代理模式&AOP
  • 原文地址:https://www.cnblogs.com/WayneZeng/p/3128121.html
Copyright © 2020-2023  润新知