Golang Read File line by line
2015-01-05 02:52
260 查看
学习什么语言都得从读文件开始,好像记得一个大神说过计算机编程就是"打开文件,操作,关闭文件"。初学Golang就记一下go语言的文件操作
Read File
Write File
Read Dir
Read File
func main(){ rw,err := os.Open("") if err != nil { panic(err) } defer rw.Close() rb := bufio.NewReader(rw) for { line, _, err := rb.ReadLine() if err == io.EOF { break } //do something fmt.Println(string(line)) } }
func main(){ rw,err := os.Open("") if err != nil { panic(err) } defer rw.Close() sb := bufio.NewScanner(rw) for sb.Scan() { //do something fmt.Println(sb.Text()) } if err := sb.Err(); err !=nil { panic(err) } }
Write File
func main(){ fw,err := os.OpenFile("",os.O_WRONLY|os.O_CREATE|os.O_APPEND,0644) if err != nil { panic(err) } defer fw.Close() wb := bufio.NewWriter(fw) wb.WriteString("hello world\n") wb.Flush() }
Read Dir
func main(){ fw,err := os.OpenFile("",os.O_WRONLY|os.O_CREATE|os.O_APPEND,0644) if err != nil { panic(err) } defer fw.Close() fileinfos, err := fw.Readdir(0) if err != nil { panic(err) } for _, fileinfo := range fileinfos { //do something fmt.Println(fileinfo.Name(),
fileinfo.Size()) } }
相关文章推荐
- read file by bash shell just as getline() in c++
- Expect script to read file line by line
- Open and read file line by line tcl tk
- Read in text file line by line php - newline not being detected
- Java 8 Stream – Read a file line by line
- bash read file line by line
- How to read file line by line?
- Shell Script Utility To Read a File Line By Line
- How to read a file line by line?
- Read file line by line (Bash shell script, sed usage)
- Bash Shell read file line by line and substring
- awk check text file line-by-line
- warning: here-document at line 17 delimited by end-of-file (wanted `EOF')
- 【已解决】R read.table()报错:incomplete final line found by readTableHeader
- [每日一答] [20151024] incomplete final line found by readTableHeader on ${fileName}原因以及解决方案
- Step By Step guide to Read XML file in Java Using SAX Parser Example
- While it is not the end of a file, output file line by line
- R:incomplete final line found by readTableHeader on
- bash报错./mq.sh: line 15: warning: here-document at line 10 delimited by end-of-file (wanted `eof')
- input01.sh: line 11: warning: here-document at line 4 delimited by end-of-file (wanted `EOF') input01.sh: line 12: syntax error: unexpected end of file