golang读取文件并逐行输出
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
openTxt("d:/Desktop/area.txt")
}
func openTxt(txt string) string {
filePath := txt
file, err := os.Open(filePath)
if err != nil {
fmt.Println("文件打开失败 = ", err)
return ""
}
defer file.Close() // 关闭文本流
reader := bufio.NewReader(file) // 读取文本数据
for {
str, err := reader.ReadString('\n')
if err ==io.EOF {
break
}
fmt.Print(str)
}
fmt.Println("文件读取结束")
return ""
}