Go语言之文件与文件夹操作

文件与文件夹

获取当前目录

1
2
3
4
import (
"os"
)
ExecPath, _ := os.Getwd()

路径拼接

1
2
3
4
import (
"path"
)
filepath2 := path.Join(ExecPath, "txt", "test.txt")

获取文件所在目录

1
2
3
4
import (
"path/filepath"
)
DicPath := filepath.Dir(mfilepath)

创建文件夹

1
2
os.Mkdir("abc", os.ModePerm)              //创建目录   
os.MkdirAll("dir1/dir2/dir3", os.ModePerm) //创建多级目录

注意

如果目录已存在,调用Mkdir创建则会报错

如果目录已存在,调用MkdirAll创建则不会报错

示例

1
2
3
4
err:= os.Mkdir("./dir1",os.ModePerm)
if err!=nil{
fmt.Println(err)
}

示例 根据日期创建文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
"os"
"path/filepath"
"time"
)

// CreateDateDir 根据当前日期来创建文件夹
func CreateDateDir(Path string) string {
folderName := time.Now().Format("20060102")
folderPath := filepath.Join(Path, folderName)
if _, err := os.Stat(folderPath); os.IsNotExist(err) {
// 必须分成两步:先创建文件夹、再修改权限
os.Mkdir(folderPath, 0777) //0777也可以os.ModePerm
os.Chmod(folderPath, 0777)
}
return folderPath
}

判断文件/文件夹是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import (
"os"
)
// 判断文件夹是否存在
func PathExists(mpath string) (bool, error) {
_, err := os.Stat(mpath)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}

删除指定目录

1
os.RemoveAll("abc")

文件

创建文件

创建文件

1
2
f1, _ := os.Create("./1.txt") 
defer f1.Close()

以读写方式打开文件,如果不存在则创建文件,等同于上面os.Create

1
2
f4, _ := os.OpenFile("./4.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
defer f4.Close()

属性获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
"fmt"
"os"
"path"
)

func main() {
ExecPath, _ := os.Getwd()
filepath2 := path.Join(ExecPath, "txt", "test.txt")
fileInfo, err := os.Stat(filepath2)
if err != nil {
fmt.Println(err)
}
fmt.Println(fileInfo.Name()) //test.txt
fmt.Println(fileInfo.IsDir()) //false 判断是否是目录
fmt.Println(fileInfo.ModTime()) //2021-04-15 11:08:05.9518876 +0800 CST 文件的修改时间
fmt.Println(fileInfo.Size()) //12 文件大小
fmt.Println(fileInfo.Mode()) // -rw-rw-rw- 读写属性
fmt.Println(fileInfo.Sys()) //&{32 {1879561846 30880164} {2384402332 30880164} {2384402332 30880164} 0 12}
}

删除指定目录下所有文件

1
os.Remove("abc/d/e/f")

重命名文件

1
os.Rename("./2.txt", "./2_new.txt")

文件读取

按行读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
"bufio"
"fmt"
"io"
"os"
"path"
"strings"
)

func readConfig() {
ExecPath, _ := os.Getwd()
filepath := path.Join(ExecPath, "nginx", "test.psvmc.cn.conf")
fmt.Println("filepath:", filepath)

f, err := os.Open(filepath)
if err != nil {
fmt.Println(err.Error())
}

//建立缓冲区,把文件内容放到缓冲区中
buf := bufio.NewReader(f)
for {
//遇到\n结束读取
b, errR := buf.ReadBytes('\n')
if errR != nil {
if errR == io.EOF {
break
}
fmt.Println(errR.Error())
}
fmt.Println(strings.TrimSpace(string(b)))
}
}

func main() {
readConfig()
}

按字符读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
"fmt"
"io/ioutil"
"os"
"path"
)

func readConfig() {
ExecPath, _ := os.Getwd()
filepath := path.Join(ExecPath, "nginx", "test.psvmc.cn.conf")
data, err := ioutil.ReadFile(filepath)
fmt.Println("filepath:", filepath)

if err != nil {
fmt.Println("读取配置文件失败", err)
return
}

datastr := string(data)
for k, v := range datastr {
if v == '{' || v == '}' {
fmt.Printf("%d %c\n", k, v)
}
}

}

func main() {
readConfig()
}

文件写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main

import (
"bufio"
"fmt"
"os"
"path"
"path/filepath"
)

// 判断文件夹是否存在
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}

// 写入文件
func WriteConfig(mfilepath string) {
strArr := new([]string)
*strArr = append(*strArr, "111")
*strArr = append(*strArr, "222")
*strArr = append(*strArr, "333")

DicPath := filepath.Dir(mfilepath)
fmt.Print("DicPath:", DicPath)

isExist, _ := PathExists(DicPath)
if !isExist {
os.MkdirAll(DicPath, os.ModePerm)
}

file, err := os.OpenFile(mfilepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("文件打开失败", err)
}
//及时关闭file句柄
defer file.Close()
//写入文件时,使用带缓存的 *Writer
write := bufio.NewWriter(file)
for i := 0; i < len(*strArr); i++ {
write.WriteString((*strArr)[i] + "\n")
}
//Flush将缓存的文件真正写入到文件中
write.Flush()
}

func main() {
ExecPath, _ := os.Getwd()
filepath2 := path.Join(ExecPath, "txt", "test.txt")
WriteConfig(filepath2)
}