一、文件和目录操作方法
文件操作
// 创建文件
os.Create(name string)
// 删除文件
os.Remove(name string)
// 使用strings.HasSuffix()判断是否包含此后缀名或者使用数组判断
// 重命名文件
os.Rename(oldpath, newpath string)
// 读取文件
os.ReadFile(name string)
// 重写文件
os.WriteFile(name string, data []byte, perm FileMode) // FileMode: os.ModePerm
目录操作
// 创建目录
os.Mkdir(name string, perm FileMode)
// 创建多级目录
os.MkdirAll(path string, perm FileMode)
// 删除目录
os.RemoveAll(path string)
// 获取当前工作目录
os.Getwd()
// 切换当前工作目录
os.Chdir(path string)
// 获取临时目录?
os.TempDir()
// 读取目录
os.ReadDir(name string)
二、文件及目录判断
// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) // os.Stat获取文件信息
if err != nil && !os.IsExist(err) {
return false
}
return true
}
// 判断所给路径是否为文件夹
func IsDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
// 判断所给路径是否为文件
func IsFile(path string) bool {
return !IsDir(path)
}
三、遍历当前目录下所有文件 (包含子目录,可指定目录)
1.遍历目录下(包含子目录)所有文件及目录
package main
import (
"fmt"
"os"
"path/filepath"
)
var cnt int
func main() {
cur_dir, _ := os.Getwd()
Walk(cur_dir)
fmt.Printf("Total files count: %d.", cnt)
}
func Walk(path string) {
dir, _ := os.ReadDir(path)
for _, file := range dir {
file_path := filepath.Join(path, file.Name())
cnt++
fmt.Printf("%-4d: %s\n", cnt, file_path)
if file.IsDir() {
Walk(file_path)
}
}
}
/**
1 : /Users/coulsonzero/Documents/Golang/Go-project/go-study/go.mod
2 : /Users/coulsonzero/Documents/Golang/Go-project/go-study/go.sum
...
217 : /Users/coulsonzero/Documents/Golang/Go-project/go-study/nowcoder-go/16-Error/GP46-RecoverPanicError.go
218 : /Users/coulsonzero/Documents/Golang/Go-project/go-study/nowcoder-go/main.go
Total count of files: 218.
*/
2.遍历目录下的所有文件及目录信息
注意:此方法会将当前工作目录也一并输出,所以数量会多一个
package main
import (
"fmt"
"os"
"path/filepath"
)
var cnt int
func WalkDir() {
pwd, _ := os.Getwd()
// 获取当前目录下的所有文件或目录信息
filepath.Walk(pwd, func(path string, info os.FileInfo, err error) error {
cnt++
fmt.Printf("%-4d. %s\n", cnt, path)
// fmt.Println(path) // 打印path信息 (带绝对路径)
// fmt.Println(info.Name()) // 打印文件或目录名(无绝对路径)
return nil
})
}
/*
1. . /Users/coulsonzero/Documents/Golang/Go-project/go-study
2 . /Users/coulsonzero/Documents/Golang/Go-project/go-study/main/Libs/json/gjson.go
...
219 . /Users/coulsonzero/Documents/Golang/Go-project/go-study/main/Libs/sort/pdqsort.go
Total count of files: 219.
*/
3.遍历当前目录下所有文件(包含子目录下)
func WalkFiles(path string) {
dir, _ := os.ReadDir(path)
for _, file := range dir {
file_path := filepath.Join(path, file.Name())
if file.IsDir() {
Walk(file_path)
} else {
cnt++
fmt.Printf("%-4d: %s\n", cnt, file_path)
}
}
}
/*
...
140 : /Users/coulsonzero/Documents/Golang/Go-project/go-study/nowcoder-go/16-Error/GP46-RecoverPanicError.go
141 : /Users/coulsonzero/Documents/Golang/Go-project/go-study/nowcoder-go/main.go
Total count of files: 141.
*/
四、移除文件
1.移除单个指定类型文件
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
var cnt int
func main() {
cur_dir, _ := os.Getwd()
// cur_dir = filepath(cur_dir, "src") // "<your-project>/src"
WalkRemoveFiles(cur_dir)
fmt.Printf("Total count of files: %d.", cnt)
}
// 移除“txt”文件
func WalkRemoveFiles(path string) {
dir, _ := os.ReadDir(path)
for _, file := range dir {
file_path := filepath.Join(path, file.Name())
if file.IsDir() {
WalkRemoveFiles(file_path)
} else {
if strings.HasSuffix(file_path, "txt") {
cnt++
fmt.Printf("%-4d: %s\n", cnt, file_path)
// err := os.Remove(file_path)
// if err != nil {
// return
// }
}
}
}
}
2.移除多个指定类型文件 & 保留指定类型文件(移除其他文件)
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
var (
cnt int
specifiedType []string = []string{"txt", "py", "js"}
retainType []string = []string{"go"}
)
func main() {
cur_dir, _ := os.Getwd()
// cur_dir = filepath(cur_dir, "src") // "<your-project>/src"
WalkRemoveFiles2(cur_dir)
fmt.Printf("Total count of files: %d.", cnt)
}
func WalkRemoveFiles2(path string) {
ContainsStr := func(arr []string, value string) bool {
for _, v := range arr {
if v == value {
return true
}
}
return false
}
print := func(file_path string) {
cnt++
fmt.Printf("%-4d: %s\n", cnt, file_path)
// os.Remove(file_path)
}
dir, _ := os.ReadDir(path)
for _, file := range dir {
file_path := filepath.Join(path, file.Name())
if file.IsDir() {
WalkRemoveFiles2(file_path)
} else {
arr := strings.Split(file_path, ".")
file_type := arr[len(arr)-1]
switch {
// 仅保留指定类型文件,删除类型为空
case len(specifiedType) == 0 && len(retainType) != 0 && !ContainsStr(retainType, file_type):
print(file_path)
// 仅删除指定类型文件,保留类型为空
case len(retainType) == 0 && len(specifiedType) != 0 && ContainsStr(specifiedType, file_type):
print(file_path)
// 保留指定类型文件的同时, 且删除指定类型文件
case len(retainType) != 0 && len(specifiedType) != 0 && (!ContainsStr(retainType, file_type) && ContainsStr(specifiedType, file_type)):
print(file_path)
default:
// print(file_path)
}
}
}
}