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语句里


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM