Skip to content

Go语言中的文件操作及读写

1033字约3分钟

Golang

2024-08-23

Go 语言中的文件操作及读写

1.文件操作

1.1 目录文件列表

使用 os.ReadDir 方法获取指定目录下的文件列表,这里需要注意对于文件列表的遍历操作,实现代码如下。

package main

import (
	"fmt"
	"os"
)

// 获取目录下的文件列表
func getDirFile(targetDir string) {
	// 读取目录下的文件和目录
	entries, err := os.ReadDir(targetDir)
	if err != nil {
		fmt.Printf("get %s directory files failed,message is %s", targetDir, err)
	}
	// 遍历文件和目录列表
	fmt.Printf("%s directory file list is:", targetDir)
	for _, entry := range entries {
		fmt.Print(" ", entry.Name())
	}
	fmt.Println()
}

// main函数调用获取文件列表的方法
func main() {
	// 获取目录下的文件列表
	targetDir := "GoFile"
	getDirFile(targetDir)
}

运行代码,能够拿到 GoFile 目录下的文件列表。

image-20240823231150612

1.2 创建文件

使用 os.Create 进行文件的创建,这里需要传递一个完整的路径或项目下的一个路径。

package main

import (
	"fmt"
	"os"
)

// 创建文件
func createFile(filePath string) {
	// 创建或打开文件
	file, err := os.Create(filePath)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("create file successfully")
	// 使用 defer 确保文件在函数退出时关闭
	defer file.Close()
}

func main() {
	// 在GoFile目录下创建文件example.txt
	createFile("GoFile/example.txt")
	// 打印出GoFile目录下的文件列表
	getDirFile("GoFile")
}

image-20240823231556474

1.3 重命名文件

使用 os.Rename() 方法进行文件的重命名操作。

package main

import (
	"fmt"
	"os"
)

// 修改文件名称
func renameFile(filePath, filePathNew string) {
	// 重命名文件
	err := os.Rename(filePath, filePathNew)
	if err != nil {
		fmt.Println("Error renaming file:", err)
		return
	}
	fmt.Println("Renamed GoFile successfully")
}

func main() {
	// 在GoFile目录下创建文件example.txt
	createFile("GoFile/example.txt")
	// 打印出GoFile目录下的文件列表
	getDirFile("GoFile")
}

image-20240823232025204

1.4 删除文件

使用 os.Remove() 进行文件的删除操作。

package main

import (
	"fmt"
	"os"
)

func deleteFile(targetFile string) {
	err := os.Remove(targetFile)
	if err != nil {
		fmt.Printf("delete file failed, message is %s", err)
	}
	fmt.Println("delete file successfully")
}

func main() {
	// 删除目录下的exampleNew.txt文件
	deleteFile("GoFile/exampleNew.txt")
	// 打印GoFile目录下的文件列表
	getDirFile("GoFile")
}

image-20240823232416651

2.文件读写

2.1 读取文件内容

读取文件内容分为两种方式:1.直接读取整个文件的内容、2.打开文件,将文件转化为 scanner 对象,逐行进行读取,实现分别如下。

使用 os.ReadFile() 读取整个文件内容。

package main

import (
	"fmt"
	"os"
)

// 读取文件(读取整个文件)
func readFile(targetFile string) {
	data, err := os.ReadFile(targetFile)
	if err != nil {
		fmt.Printf("read file failed, message is %s", err)
	}
	fmt.Println(string(data))
}

func main() {
    // 读取整个文件的内容
	readFile("GoFile/无衣.txt")
}

image-20240823233132611

使用 os.Open() 打开文件后,将文件转化为 scanner 后逐行进行读取。

package main

import (
	"bufio"
	"fmt"
	"os"
)

// 读取文件(逐行读取文件)
func readFileLine(targetFile string) {
	// 打开文件
	file, err := os.Open(targetFile)
	if err != nil {
		fmt.Printf("read file failed, message is %s", err)
	}
	defer file.Close()
	// 构造一个Scanner
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
		fmt.Println("--------------------------------")
	}

	if err := scanner.Err(); err != nil {
		fmt.Printf("change file to scanner failed,message is %s", err)
	}
}

func main() {
	readFileLine("GoFile/无衣.txt")
}

image-20240823233650777

2.2 写入文件

使用 os.OpenFile 以追加模式打开文件,并使用 WriteString 追加内容。

package main

import (
	"fmt"
	"os"
)


func wrirteFile(targetFile string) {
	// 打开文件,如文件不存在会报错
	file, err := os.OpenFile(targetFile, os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		fmt.Printf("write file to %s failed,message is %s", targetFile, err)
	}
	defer file.Close()

	_, err = file.WriteString("\n南歌EuanSu 要好好学习Golang")
	if err != nil {
		fmt.Printf("write file %s failed,message is %s", targetFile, err)
	}
	fmt.Println("write file successfully")
}

func main() {
	wrirteFile("GoFile/无衣.txt")
}

image-20240823234230637