17 Go file operations

Overview

        In the previous section, we introduced Go’s reflection, including: reflect.TypeOf, reflect.ValueOf, reflect.Value, etc. In this section, we will introduce Go’s file operations. In the Go language, a file is an abstract concept that represents a continuous sequence of bytes. File operations mainly include: file creation, reading, writing, deletion, directory creation, deletion, file traversal, etc. The Go language provides many built-in functions and packages that make file operations very simple and efficient.

read file

        To read a file, you need to open the file first. To open a file, you can use the os.Open() function, which returns a file object of type *os.File, representing the opened file. To read the contents of a file, you can use the functions provided by the os package or the bufio package.

        In the sample code below, we first open the file test.txt using the os.Open() function. Then, we use the bufio.NewScanner function to create a Scanner object scanner and read the file line by line. If an error occurs while reading the file, the error information can be obtained through the scanner.Err() function.

package main

import "os"
import "fmt"
import "bufio"

func main() {
    // 打开文件
    file, err := os.Open("test.txt")
    if err != nil {
        fmt.Println("Open failed: ", err)
        return
    }

    defer file.Close()

    // 逐行读取文件
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()
        // 处理每一行数据
        fmt.Println("line data: ", line)
    }

    if err := scanner.Err(); err != nil {
        // 处理读取错误
        fmt.Println("Read failed: ", err)
    }
}

write file

        To write to a file, you can use the Create() function provided by the os package to create a new file, and use the Write() function or WriteString() function to write data.

        In the sample code below, we first create the file test.txt using the os.Create() function. Then, we used the WriteString() function to write the string "Hello, CSDN". Finally, we close the file through the defer statement and release system resources.

package main

import "os"
import "fmt"

func main() {
    // 创建文件
    file, err := os.Create("test.txt")
    if err != nil {
        fmt.Println("Create failed: ", err)
        return
    }

    defer file.Close()

    text := "Hello, CSDN"
    // 向文件中写入字符串
    _, err = file.WriteString(text)
    if err != nil {
        fmt.Println("Write failed: ", err)
    }
}

        When performing file reading and writing operations, you need to pay attention to the following points:

        ​ ​ 1. After opening the file, you must remember to close the file to release resources. You can use the defer statement to ensure that the file is closed when the function ends.

        ​ ​ 2. When reading or writing files, you need to check whether any errors occur and perform appropriate error handling.

Delete Files

        ​​​​To delete a file, you can use the os.Remove() function.

package main

import "os"
import "fmt"

func main() {
    err := os.Remove("test.txt")  
    if err != nil {
        fmt.Println("Remove failed:", err)
    } else {
        fmt.Println("Remove success")
    }
}

Directory operations

        Directory operations include: creating a directory, deleting a directory, determining whether the directory exists, etc.

        In the sample code below, we first create a new directory named test using the os.Mkdir() function. The first parameter is the path to the directory, and the second parameter is the permission mode of the directory (0755 means the owner has read, write, and execute permissions, and the group and other users have read and execute permissions). Next, we determine whether the directory exists through the os.Stat() function. If it exists, call the os.Remove() function to delete the directory just created.

package main

import "os"
import "fmt"

func main() {
    // 创建目录
    err := os.Mkdir("test", 0755)
    if err != nil {
        fmt.Println("Mkdir failed:", err)
        return
    } else {
        fmt.Println("Mkdir success")
    }

    // 判断目录是否存在
    _ , err2 := os.Stat("test")
    if err2 == nil {
        // 删除目录
        err = os.Remove("test")
        if err != nil {
            fmt.Println("Remove failed:", err)
        } else {
            fmt.Println("Remove success")
        }
    } else {
        fmt.Println("Path not exist")
    }
}

Traverse files in a directory

        In Go language, you can use the Readdir function in the os package to read the contents of the directory. The Readdir function returns a slice of type []os.DirEntry, which contains information about all files and subdirectories in the directory.

        In the sample code below, we use the os.Open function to open a directory named doc and the Readdir function to list all the files in it. Then, by looping over the files slice, you can print out the name of each file. Note: When using the Readdir function, passing -1 as a parameter will return all files, including hidden files.

package main

import "os"
import "fmt"

func main() {
    // 打开目录
    dir, err := os.Open("doc")
    if err != nil {
        fmt.Println("Open failed:", err)
        return
    }

    defer dir.Close()

    // 读取目录
    files, err := dir.Readdir(-1)
    if err != nil {
        fmt.Println("Readdir failed:", err)
    } else {
        // 遍历目录下文件
        for _, file := range files {
            fmt.Println(file.Name())
        }
    }
}

Guess you like

Origin blog.csdn.net/hope_wisdom/article/details/134631288