Go语言读取文件内容

简介

读取文件内容在每个语言里面都有,go语言中主要注意文件读完后会返回一个异常 io.EOF,根据这个异常去判断就可以了

代码实现

go 复制代码
package main

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

func main() {
	lines := Read("test.txt")
	for _, line := range lines {
		fmt.Println(line)
	}
}

// ReadFile 文件读取操作
// 按行读取文件
func ReadFile(file io.Reader) []string {
	var result []string
	reader := bufio.NewReader(file)
	for {
		line, _, err := reader.ReadLine()

		if err != nil && err != io.EOF {
			panic(err)
		}
		if err == io.EOF { //读取完了
			break
		}

		result = append(result, string(line))

	}
	return result
}

func Read(fileName string) []string {

	file, err := os.Open(fileName)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	return ReadFile(file)
}

func ReadBytes(fileName string) []byte {
	data, err := os.ReadFile(fileName)
	if err != nil {
		return nil
	}
	return data
}

测试

shell 复制代码
$ cat test.txt 
hello shura
end

执行程序,输出

text 复制代码
hello shura
end

总结

以上就是go读取文件内容的代码了,平时作为自己的一个小工具库用


欢迎关注,学习不迷路!

相关推荐
??? Meggie4 分钟前
【Python】保持Selenium稳定爬取的方法(防检测策略)
开发语言·python·selenium
酷爱码2 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼2 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
喵先生!3 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ4 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
xMathematics4 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
yuanManGan6 小时前
C++入门小馆: 深入了解STLlist
开发语言·c++
北极的企鹅886 小时前
XML内容解析成实体类
xml·java·开发语言
BillKu6 小时前
Vue3后代组件多祖先通讯设计方案
开发语言·javascript·ecmascript
Python自动化办公社区6 小时前
Python 3.14:探索新版本的魅力与革新
开发语言·python