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

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

内容简介:暂时未整理

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)

}

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

查看所有标签

猜你喜欢:

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

An Introduction to Genetic Algorithms

An Introduction to Genetic Algorithms

Melanie Mitchell / MIT Press / 1998-2-6 / USD 45.00

Genetic algorithms have been used in science and engineering as adaptive algorithms for solving practical problems and as computational models of natural evolutionary systems. This brief, accessible i......一起来看看 《An Introduction to Genetic Algorithms》 这本书的介绍吧!

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

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具