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

  • 相关阅读:
    margin:0 auto; 为什么会失效
    vue 登录滑块验证
    layui table 添加序号列
    纯css :after 菜单后面添加“<”
    设置div为不可点击
    ubuntu中root用户在图形界面登录
    ubuntu root用户无法登录filezilla的问题
    ubuntu无法用putty登录
    解决ubuntu和windows电脑之间无法复制粘贴问题
    E: Unable to locate package ubuntu
  • 原文地址:https://www.cnblogs.com/WayneZeng/p/3128121.html
Copyright © 2011-2022 走看看