第八章 文件操作
文章目录
- 第八章 文件操作
- 1 文件读取
- 1 将文件整个读取内存
- 2 按字节读取文件
1 文件读取
1 将文件整个读取内存
类似于python的
with open(filename, mode='rt', encoding='utf-8') as f:res = f.read()
go中的书写方式:
- 方式一:
package mainimport ("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 mainimport ("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