使用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数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间。下面话不多说,来看看详细的介绍吧。 以下实例在变量赋值时 Number 对...

Python之pandas读写文件乱码的解决方法

python读写文件有时候会出现   ‘XXX'编码不能打开XXX什么的,用记事本打开要读取的文件,另存为UTF-8编码,然后再用py去读应该可以了。如果还不行,那...

Django项目后台不挂断运行的方法

方法一: 1、进入项目目录下,运行下面程序: nohup python manage.py runserver 0.0.0.0:5008 & nohup(no hang up)用...

PyTorch学习笔记之回归实战

PyTorch学习笔记之回归实战

本文主要是用PyTorch来实现一个简单的回归任务。 编辑器:spyder 1.引入相应的包及生成伪数据 import torch import torch.nn.functio...

Python单元测试工具doctest和unittest使用解析

Python单元测试工具doctest和unittest使用解析

Python标准库包含两个测试工具。 doctest:一个简单的模块,为检查文档而设计,但也适合用来编写单元测试。 unittest:一个通用的测试框架。 一、使用doctest进行单元...