【go笔记】目录操作

简介: 【go笔记】目录操作

基本目录操作

涉及:创建目录、重命名目录、删除目录

package main
import (
  "fmt"
  "os"
  "time"
  "path/filepath"
)
func CreateDir(Path string) string {
  // 创建以当天日期命名的目录
  dirName := time.Now().Format("20060102")
  dirPath := filepath.Join(Path, dirName)
  if _,err := os.Stat(dirPath); os.IsNotExist(err) {
    // 创建目录
    os.MkdirAll(dirPath, os.ModePerm)
    // 修改权限
    os.Chmod(dirPath, 0777)
  }
  return dirPath
}
func main() {
  path,err := os.Getwd()
  if err != nil {
    fmt.Println(err)
  }
  path = CreateDir(path)
  fmt.Println(path)
  // 创建子目录。20211219/新文件夹/dic
  os.MkdirAll(filepath.Join(path, "新文件夹/dic"), os.ModePerm)
  // 目录重命名。20211219/newfolder/dic
  os.Rename(filepath.Join(path, "新文件夹"), filepath.Join(path, "newfolder"))
  //删除目录。如果有子目录则不删除
  os.Remove(filepath.Join(path, "newfolder/dic"))
}

遍历目录

package main
import (
  "fmt"
  "os"
  "path/filepath"
)
func visit(path string, f os.FileInfo, err error) error {
  fmt.Printf("%s \n", path)
  return nil
}
func main() {
  // 遍历当前目录
  if root, err := os.Getwd(); err == nil {
    // filepath.Walk()用于遍历指定目录,该方法接收两个参数,一个是根目录root,另一个是递归的回调函数walkFunc
    // 目录文件较多时,Walk()效率低下
    err := filepath.Walk(root, visit)
    if err != nil {
      fmt.Println(err)
    }
  }
}

参考文章

  • 汪明 - 《Go并发编程实战》清华大学出版社

本文来自博客园,作者:花酒锄作田,转载请注明原文链接:https://www.cnblogs.com/XY-Heruo/p/15707734.html

相关文章
|
4月前
|
SQL 前端开发 Go
编程笔记 GOLANG基础 001 为什么要学习Go语言
编程笔记 GOLANG基础 001 为什么要学习Go语言
|
1月前
|
SQL 关系型数据库 MySQL
【go笔记】使用sqlx操作MySQL
【go笔记】使用sqlx操作MySQL
|
1月前
|
Go
【go笔记】标准库-strconv
【go笔记】标准库-strconv
|
1月前
|
网络协议 前端开发 Go
[go笔记]websocket入门
[go笔记]websocket入门
|
1月前
|
网络协议 Go
【go笔记】简单的http服务
【go笔记】简单的http服务
|
1月前
|
网络协议 Go
【go笔记】TCP编程
【go笔记】TCP编程
|
1月前
|
Go 索引
【go笔记】标准库-strings
【go笔记】标准库-strings
|
1月前
|
Go
【go笔记】使用标准库flag解析命令行参数
【go笔记】使用标准库flag解析命令行参数
|
1月前
|
Linux 编译器 Go
【go笔记】从安装到helloworld
【go笔记】从安装到helloworld
|
4月前
|
JSON 自然语言处理 网络协议
【字节跳动青训营】后端笔记整理-2 | Go实践记录:猜谜游戏,在线词典,Socks5代理服务器
猜数字游戏也算是入门一门编程语言必写的程序了。通过这个程序,我们可以熟悉Go语言中的输入输出、流程控制与随机函数的调用。
67 2