go语言csv文件的读取与写入

栏目: Go · 发布时间: 4年前

内容简介:暂时未整理

go语言csv文件的读取

暂时未整理

package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    //准备读取文件
    fileName := "D:\\gotest\\src\\source\\test.csv"
    fs, err := os.Open(fileName)
    if err != nil {
        log.Fatalf("can not open the file, err is %+v", err)
    }
    defer fs.Close()

    r := csv.NewReader(fs)
    //针对大文件,一行一行的读取文件
    for {
        row, err := r.Read()
        if err != nil && err != io.EOF {
            log.Fatalf("can not read, err is %+v", err)
        }
        if err == io.EOF {
            break
        }
        fmt.Println(row)
    }

    //针对小文件,也可以一次性读取所有的文件
    //注意,r要重新赋值,因为readall是读取剩下的
    fs1, _ := os.Open(fileName)
    r1 := csv.NewReader(fs1)
    content, err := r1.ReadAll()
    if err != nil {
        log.Fatalf("can not readall, err is %+v", err)
    }
    for _, row := range content {
        fmt.Println(row)
    }

    //创建一个新文件
    newFileName := "D:\\gotest\\src\\source\\newfile.csv"
    //这样打开,每次都会清空文件内容
    //nfs, err := os.Create(newFileName)

    //这样可以追加写
    nfs, err := os.OpenFile(newFileName, os.O_RDWR|os.O_CREATE, 0666)
    if err != nil {
        log.Fatalf("can not create file, err is %+v", err)
    }
    defer nfs.Close()
    nfs.Seek(0, io.SeekEnd)

    w := csv.NewWriter(nfs)
    //设置属性
    w.Comma = ','
    w.UseCRLF = true
    row := []string{"1", "2", "3", "4", "5,6"}
    err = w.Write(row)
    if err != nil {
        log.Fatalf("can not write, err is %+v", err)
    }
    //这里必须刷新,才能将数据写入文件。
    w.Flush()

    //一次写入多行
    var newContent [][]string
    newContent = append(newContent, []string{"1", "2", "3", "4", "5", "6"})
    newContent = append(newContent, []string{"11", "12", "13", "14", "15", "16"})
    newContent = append(newContent, []string{"21", "22", "23", "24", "25", "26"})
    w.WriteAll(newContent)

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Seasoned Schemer

The Seasoned Schemer

Daniel P. Friedman、Matthias Felleisen / The MIT Press / 1995-12-21 / USD 38.00

drawings by Duane Bibbyforeword and afterword by Guy L. Steele Jr.The notion that "thinking about computing is one of the most exciting things the human mind can do" sets both The Little Schemer (form......一起来看看 《The Seasoned Schemer》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码