使用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中__init__()方法的高级应用

通过工厂函数对 __init__() 加以利用 我们可以通过工厂函数来构建一副完整的扑克牌。这会比枚举所有52张扑克牌要好得多,在Python中,我们有如下两种常见的工厂方法: &...

Python+OpenCV图片局部区域像素值处理详解

背景故事:我需要对一张图片做一些处理,是在图像像素级别上的数值处理,以此来反映图片中特定区域的图像特征,网上查了很多,大多关于opencv的应用教程帖子基本是停留在打开图片,提取像素重新...

python 实现一次性在文件中写入多行的方法

将要写入的内容 构造 进一个list 中,使用writelines()方法 一次性写入。 file_w.writelines(list) file_w.flush() file.c...

windows安装TensorFlow和Keras遇到的问题及其解决方法

windows安装TensorFlow和Keras遇到的问题及其解决方法

  安装TensorFlow在Windows上,真是让我心力交瘁,想死的心都有了,在Windows上做开发真的让人发狂。   首先说一下我的经历,本来也就是起初,网上说python3.7...

Python实现的基于优先等级分配糖果问题算法示例

Python实现的基于优先等级分配糖果问题算法示例

本文实例讲述了Python实现的基于优先等级分配糖果问题算法。分享给大家供大家参考,具体如下: 问题: 有n个人,每个人有一定的优先等级,等级高的人要比身边等级低得人得到的多,每个人都不...