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 ", contents)
//}

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

//注意:if的条件里可以赋值
//if的条件里赋值的变量作用域就在这个if语句里
原文地址:https://www.cnblogs.com/lty-fly/p/12047672.html