下面算是一个go写文件,遍历文件夹的小demo
中午一个同学找到我,
问我
py的话很简单,几行代码

import os

path = os.getcwd()
filenames = os.listdir(path)
print(filenames)

for f in filenames:
    with open("afile.txt", "a", encoding="utf8")as fp:
        fp.write(f + "\n")

我选择了用go

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "os/exec"
    "path"
    "path/filepath"
    "strings"
    "time"
)

// getCurrentPath 获取路径
func getCurrentPath() string {
    s, err := exec.LookPath(os.Args[0])
    if err != nil {
        fmt.Println("err:=", err.Error())
        os.Exit(0)
    }
    i := strings.LastIndex(s, "\\")
    pat := string(s[0 : i+1])
    return pat
}

// WriteFile 写文件
func WriteFile(lines []string) {
    f, err := os.Create("afile.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    for _, line := range lines {
        _, err := f.WriteString(line + "\n")
        if err != nil {
            log.Fatal(err)
        }
    }
}

// ListDir 获取指定路径下的所有文件,不进入子目录
func ListDir(dir, suffix string) (files []string, err error) {
    files = []string{}

    _dir, err := ioutil.ReadDir(dir)
    if err != nil {
        return nil, err
    }

    suffix = strings.ToLower(suffix) //匹配后缀

    for _, _file := range _dir {
        if _file.IsDir() {
            continue //忽略目录
        }
        if len(suffix) == 0 || strings.HasSuffix(strings.ToLower(_file.Name()), suffix) {
            //文件后缀匹配
            files = append(files, path.Join(dir, _file.Name()))
        }
    }

    return files, nil
}

// WalkDir 获取指定路径下以及所有子目录下的所有文件,可匹配后缀过滤(suffix为空则不过滤)
func WalkDir(dir, suffix string) (files []string, err error) {
    files = []string{}

    err = filepath.Walk(dir, func(fname string, fi os.FileInfo, err error) error {
        if fi.IsDir() {
            //忽略目录
            return nil
        }

        if len(suffix) == 0 || strings.HasSuffix(strings.ToLower(fi.Name()), suffix) {
            //文件后缀匹配
            files = append(files, fname)
        }

        return nil
    })

    return files, err
}
func main() {
    currentPath := getCurrentPath()
    fmt.Println("输入0,不递归遍历子目录, 输入1, 递归遍历子目录")
    i := 0
    fmt.Scanf("%d", &i)

    var dirs []string

    if i == 0 {
        dirs, _ = ListDir(currentPath, "")
    } else if i == 1 {
        dirs, _ = WalkDir(currentPath, "")
    } else {
        fmt.Println("input illegal")
        time.Sleep(time.Second * 3)
        os.Exit(1)
    }
    fmt.Println(dirs)
    var filename []string
    replacePath := currentPath + "/"
    for _, f := range dirs {
        temp := strings.Replace(f, replacePath, "", 1)
        temp = strings.Replace(temp, currentPath, "", 1)
        filename = append(filename, temp)
        fmt.Println(temp)
    }
    fmt.Println(filename)
    WriteFile(filename)
}

分类: go

站点统计

  • 文章总数:309 篇
  • 分类总数:19 个
  • 标签总数:190 个
  • 运行天数:975 天
  • 访问总数:73211 人次

浙公网安备33011302000604

辽ICP备20003309号