목차
Reading CSV files
Writing CSV files
Handling CSV with headers (struct mapping)
Dealing with commas and quotes
백엔드 개발 Golang Golang에서 CSV 파일 작업 방법

Golang에서 CSV 파일 작업 방법

Sep 07, 2025 am 01:59 AM
golang CSV 파일

Go的encoding/csv包可轻松处理CSV文件读写操作。1. 读取CSV文件时,使用os.Open打开文件并用csv.NewReader解析,可通过ReadAll()一次性读取或Read()逐行读取以节省内存;2. 写入CSV文件时,使用os.Create创建文件并用csv.NewWriter写入数据,需调用Flush()确保数据写入,或使用WriteAll()批量写入;3. 处理带标题的结构化数据时,可手动将记录映射到struct,如跳过首行标题并解析字段,或使用第三方库实现自动绑定;4. 对于包含逗号、换行或引号的字段,csv包会自动处理转义,必要时可通过设置Comma字段更改编码分隔符。Go的csv包已覆盖大多数场景,结合外部库可实现更高级功能。

How to work with CSV files in golang

Working with CSV files in Go is straightforward thanks to the built-in encoding/csv package. Whether you're reading from or writing to CSV files, Go provides clean and efficient tools. Here's how to handle common CSV operations.

Reading CSV files

To read a CSV file, you open the file and wrap a csv.Reader around it. The reader parses each line into a slice of strings.

package main

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

func main() {
    file, err := os.Open("data.csv")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    reader := csv.NewReader(file)
    records, err := reader.ReadAll()
    if err != nil {
        fmt.Println("Error reading CSV:", err)
        return
    }

    for _, record := range records {
        fmt.Println(record) // Each record is a []string
    }
}
  • Use Read() instead of ReadAll() if you want to process one line at a time, which is more memory-efficient for large files.
  • The first row is treated like any other unless you handle it separately (e.g., as headers).

Writing CSV files

Writing to a CSV file is just as simple. You create a csv.Writer and feed it slices of strings.

package main

import (
    "encoding/csv"
    "os"
)

func main() {
    file, err := os.Create("output.csv")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    writer := csv.NewWriter(file)
    defer writer.Flush()

    data := [][]string{
        {"Name", "Age", "City"},
        {"Alice", "30", "New York"},
        {"Bob", "25", "Los Angeles"},
    }

    for _, record := range data {
        if err := writer.Write(record); err != nil {
            fmt.Println("Error writing record:", err)
            return
        }
    }
}
  • Always call writer.Flush() to ensure all data is written to the file.
  • You can write all at once using writer.WriteAll(data) if you have the full dataset ready.

Handling CSV with headers (struct mapping)

For structured data, it’s common to map CSV rows to structs. While Go’s standard library doesn’t do this automatically, you can combine Read() with manual parsing.

type Person struct {
    Name string
    Age  int
    City string
}

file, _ := os.Open("people.csv")
defer file.Close()

reader := csv.NewReader(file)
records, _ := reader.ReadAll()

var people []Person

for i, record := range records {
    if i == 0 {
        continue // Skip header
    }
    age, _ := strconv.Atoi(record[1])
    people = append(people, Person{
        Name: record[0],
        Age:  age,
        City: record[2],
    })
}
  • This approach gives you control but requires manual field mapping.
  • For automatic struct tagging, consider third-party libraries like github.com/gocarina/gocsv or github.com/jszwec/csvutil.

Dealing with commas and quotes

CSV files often contain fields with commas, newlines, or quotes. The csv.Reader and csv.Writer handle these automatically by default.

  • Fields like "Smith, John" are correctly parsed as a single field.
  • The writer will quote fields when necessary (e.g., if they contain commas or newlines).

If you need to customize the delimiter (e.g., use semicolons), change the Comma field:

reader := csv.NewReader(file)
reader.Comma = ';' // For semicolon-separated files

Same applies to csv.Writer.


Basically, Go’s encoding/csv package covers most use cases. Read line by line for large files, use structs with manual mapping for typed data, and let the package handle escaping. For more advanced scenarios like automatic struct binding, external libraries can save time.

위 내용은 Golang에서 CSV 파일 작업 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Stock Market GPT

Stock Market GPT

더 현명한 결정을 위한 AI 기반 투자 연구

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제

PHP에서 CSV 파일을 읽는 방법은 무엇입니까? PHP에서 CSV 파일을 읽는 방법은 무엇입니까? Aug 29, 2025 am 08:06 AM

toreadacsvfileInphp, usefopen () tooptrefile, fgetcsv () inalooptoreadeachrowasanarray, andfclose () tocloseit; handleheaderswithaseparatefgetcsv () CallandspecifyDelimitersSasneed, resproperfilepathsandutfocialingforspocialingforsporspocialing.

Golang 바이너리에 정적 자산을 포함시키는 방법 Golang 바이너리에 정적 자산을 포함시키는 방법 Aug 30, 2025 am 04:50 AM

Go의 임베드 패키지를 사용하면 정적 리소스를 이진 파일에 직접 포함시킬 수 있습니다. Go1.16에서 시작하여 // go : intembed directive wefore tefore of mariables, 단일 파일, 여러 파일 또는 전체 디렉토리를 포함 시키거나 문자열, [] byte 또는 embed.fs 유형을 지원할 수 있습니다. 임베디드 함량은 컴파일 시간에 이진으로 고정화됩니다. 경로는 존재해야하며 사례에 민감합니다. Go-Bindata와 같은 타사 도구 대신 Embed를 사용하는 것이 좋습니다. 이 방법은 간단하고 효율적이며 표준 관행이되었습니다.

Golang에서 파일을 어떻게 읽고 쓰나요? Golang에서 파일을 어떻게 읽고 쓰나요? Sep 21, 2025 am 01:59 AM

goprovidessimpleanfilefile handlingsingtheosandbufiopackages.toreadasmallfileentirely, useos.readfile, whithloadsTecontintomemorySafelyAntomatically ManagestomanagesTomanagesFileOperations.forlageFilesorincrementalprocessing, bufio.scannerallows-by-lyiner

Golang에서 사용되는 빈 구조 구조 {}는 무엇입니까? Golang에서 사용되는 빈 구조 구조 {}는 무엇입니까? Sep 18, 2025 am 05:47 AM

Struct {}는 GO의 필드리스 구조로 제로 바이트를 차지하며 데이터가 필요하지 않은 시나리오에서 종종 사용됩니다. Goroutine 동기화와 같은 채널의 신호로 사용됩니다. 2. 효율적인 메모리에서 주요 존재 검사를 달성하기 위해 값 유형의 맵 모음으로 사용됩니다. 3. 종속성 주입 또는 조직 기능에 적합한 정의 가능한 상태없는 방법 수신기. 이 유형은 제어 흐름과 명확한 의도를 표현하는 데 널리 사용됩니다.

Golang의 RabbitMQ와 같은 메시지 대기열과 통합하는 방법 Golang의 RabbitMQ와 같은 메시지 대기열과 통합하는 방법 Sep 02, 2025 am 07:46 AM

답은 AMQP091-GO 라이브러리를 사용하여 RabbitMQ를 연결하고, 대기열 및 스위치를 선언하고, 메시지를 안전하게 게시하고, 메시지 소비를 QOS 및 수동 승인 및 수동 메커니즘을 다시 연결하여 GO에서 안정적인 메시지 대기열 통합을 달성하는 것입니다. 완전한 예에는 연결, 생산, 소비 및 오류 처리 프로세스가 포함되어 메시지가 손실되지 않도록하고 연결이 끊기 및 재 연결을 지원하고 Docker를 통해 RabbitMQ를 실행하여 엔드 투 엔드 통합을 완료합니다.

Golang 웹 서버의 맥락에서 미들웨어는 무엇입니까? Golang 웹 서버의 맥락에서 미들웨어는 무엇입니까? Sep 16, 2025 am 02:16 AM

MiddlewareWebServersErsectionstttprequestsBeeReachtheHandler, enableRusableCross-CuttingFunctionality; workgrappingHandlerstoaddpre-andpost-processinglogicsuchaslogging, Authentication, Cors, OrerrorRecovery 및 Canbechai

Golang에서 테이블 중심 테스트 란 무엇입니까? Golang에서 테이블 중심 테스트 란 무엇입니까? Aug 28, 2025 am 01:38 AM

Table-DriventestingingingingingoIsapattern ThatusesAdattructure, 일반적으로 asliceofstructs, todefinemultipletestescasess withinpectedoutputs, withintesametestLogicAcasesInalOOp, withleduceCodeduclationAndimproveStainabestation;

Golang 응용 프로그램에서 우아한 셧다운을 어떻게 처리합니까? Golang 응용 프로그램에서 우아한 셧다운을 어떻게 처리합니까? Sep 21, 2025 am 02:30 AM

gracefulshutdownsingoapplicationseentialsiverforreliable, ac

See all articles