使用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的Fraction类会给你很大的帮助。在该指南中,我将提供一些有趣的实例,用于展示如何处理分数,突出显示一些很酷的功能。 1 基础 F...

如何使用VSCode愉快的写Python于调试配置步骤

如何使用VSCode愉快的写Python于调试配置步骤

在学习Python的过程中,一直没有找到比较趁手的第三方编辑器,用的最多的还是Python自带的编辑器。由于本人用惯了宇宙第一IDE(Visual Studio),所以当Visual S...

python简单实现基于SSL的IRC bot实例

本文实例讲述了python简单实现基于SSL的 IRC bot。分享给大家供大家参考。具体如下: #!/usr/bin/python # -*- coding: utf8 -*- i...

Python的numpy库中将矩阵转换为列表等函数的方法

这篇文章主要介绍Python的numpy库中的一些函数,做备份,以便查找。 (1)将矩阵转换为列表的函数:numpy.matrix.tolist() 返回list列表 Examples...

Python学习笔记之函数的定义和作用域实例详解

本文实例讲述了Python函数的定义和作用域。分享给大家供大家参考,具体如下: 定义函数 默认参数: 可以向函数中添加默认参数,以便为在函数调用中未指定的参数提供默认值 # 如果调用...