第八章:文件操作

第八章 文件操作

1 文件读取

1 将文件整个读取内存

类似于python的

with open(filename, mode='rt', encoding='utf-8') as f:
    res = f.read()

go中的书写方式:

  • 方式一:
package main

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

func main() {
	// 打开文件,以只读的方式打开
	file, err := os.Open("C:\\Users\\YangYi\\Desktop\\动作.")
	if err != nil {
		//println(err)  // (0x2a0ba0,0xc000076330)
		log.Panic(err)  // 使用这种方式打印错误
		/*
		2022/03/17 08:49:31 open C:\Users\YangYi\Desktop\动作.: The system cannot find the file specified.
		panic: open C:\Users\YangYi\Desktop\动作.: The system cannot find the file specified
		*/
		//panic(err)
	}
	defer file.Close()

	content, err := ioutil.ReadAll(file)  // 类似于python中的f.read()
	fmt.Println(string(content))
}
  • 方式二:
package main

import (
	"fmt"
	"io/ioutil"
	"log"
)

func main() {
	filepath := "C:\\Users\\YangYi\\Desktop\\动作.txt"

	content ,err :=ioutil.ReadFile(filepath)  // 直接读取filepath文件中的内容
	if err !=nil {
		log.Panic(err)
	}

	fmt.Println(string(content))
}

2 按字节读取文件

参考地址:https://segmentfault.com/a/1190000017918542

posted @   YangYi215  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示