open abc.txt: The system cannot find the file specified

使用io/ioutil包读取文件时报错:open abc.txt: The system cannot find the file specified

原因是:ioutil.ReadFile()这个方法需要传入决绝路径的文件名

代码:

const filename  = "E:\\GoWorks\\Golang\\src\\if\\abc.txt"
//const filename = "abc.txt" //这样写会报错
//contents, err := ioutil.ReadFile(filename) //读取文件
//if err != nil {
// fmt.Println("err=",err)
//} else {
// fmt.Printf("%s\n", contents)
//}

//上面的写法可以改为:
if contents, err := ioutil.ReadFile(filename); err != nil {
fmt.Println("err=", err)
} else {
fmt.Printf("%s\n", contents)
}

//注意:if的条件里可以赋值
//if的条件里赋值的变量作用域就在这个if语句里
posted @ 2019-12-16 10:06  水滴月  阅读(4283)  评论(0编辑  收藏  举报