使用go和python递归删除.ds store文件的方法

yipeiwu_com5年前Python基础

python版本:

复制代码 代码如下:

#!/usr/bin/env python
import os, sys;

def walk(path):
  print "cd directory:"+path

  for item in os.listdir(path):
    try:
      if(item == ".DS_Store"):
        global count
        count = count+1
        print " find file .Ds_Store"
        os.remove(path+"/"+item)
      else:
        if(os.path.isdir(path+"/"+item)):
          print " "+path+"/"+item+" is directory"
          walk(path+"/"+item)
        else:
          print " "+path+"/"+item+" is file"
    except OSError,e:
      print e

 
if __name__=='__main__':
  count = 0
  if(len(sys.argv)>1):
    root_dir = sys.argv[1]
  else:
    root_dir = os.getcwd()
  walk(root_dir)
  print "\ntotal number:"+str(count)

go语言版本:

复制代码 代码如下:

package main

import (
  "flag"
  "fmt"
  "os"
  "path/filepath"
)

func getFilelist(path string) int {
  count := 0
  err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {

    if f == nil {
      return err
    }

    if f.IsDir() {
      fmt.Printf("cd directry %s\n", path)
      return nil
    }

    if f.Name() == ".DS_Store" {
      count++
      println(" " + f.Name() + " is deleted")
      os.Remove(path)
    }

    return nil
  })

  if err != nil {
    fmt.Printf("filepath.Walk() returned %v\n", err)
  }
  return count
}

func main() {
  flag.Parse()
  root := flag.Arg(0)
  count := 0
  if root == "" {
    crurrent_dir, _ := filepath.Abs(".")
    count = getFilelist(crurrent_dir)
  } else {
    count = getFilelist(root)
  }
  fmt.Printf("\n\n total number:%d\n", count)
}

相关文章

Python通用循环的构造方法实例分析

本文实例讲述了Python通用循环的构造方法。分享给大家供大家参考,具体如下: 1.交互循环 是无限循环的一种,允许用户通过交互的方式程序的特定部分; def main(): s...

Python 实现递归法解决迷宫问题的示例代码

Python 实现递归法解决迷宫问题的示例代码

迷宫问题 问题描述: 迷宫可用方阵 [m, n] 表示,0 表示可通过,1 表示不能通过。若要求左上角 (0, 0) 进入,设计算法寻求一条能从右下角 (m-1, n-1) 出去的路径。...

pyinstaller 3.6版本通过pip安装失败的解决办法(推荐)

pyinstaller 3.6版本通过pip安装失败的解决办法(推荐)

本机中原pyinstaller版本为3.5版本,本打算通过 pip install --upgrade pyinstaller进行升级,竟然报错,后面卸载再重新安装也一样报错,没办法看来...

Python正则表达式分组概念与用法详解

本文实例讲述了Python正则表达式分组概念与用法。分享给大家供大家参考,具体如下: 正则表达式分组 分组就是用一对圆括号“()”括起来的正则表达式,匹配出的内容就表示一个分组。从正则...

对python:循环定义多个变量的实例详解

对python:循环定义多个变量的实例详解

我们可能会时长碰到这样一个场景,计算得到一个非固定值,需要根据这个值定义相同数量个变量。 实现方式的核心是exec函数,exec函数可以执行我们输入的代码字符串。 exec函数的简单例子...