目次
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 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、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

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

ホットトピック

Golangで使用される空のstruct struct {}は何ですか Golangで使用される空のstruct struct {}は何ですか Sep 18, 2025 am 05:47 AM

struct {}はgoのフィールドレス構造であり、ゼロバイトを占有し、データが不要なシナリオでよく使用されます。 Goroutine同期など、チャネル内の信号として使用されます。 2。効率的なメモリの重要な存在チェックを実現するために、値の種類のコレクションとして使用されます。 3.依存関係の注入または組織機能に適した定義可能なステートレスメソッドレシーバー。このタイプは、制御フローと明確な意図を表現するために広く使用されています。

Golangでファイルをどのように読み取り、書き込みますか? Golangでファイルをどのように読み取り、書き込みますか? Sep 21, 2025 am 01:59 AM

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

Golang Webサーバーのコンテキストのミドルウェアは何ですか? Golang Webサーバーのコンテキストのミドルウェアは何ですか? Sep 16, 2025 am 02:16 AM

ミドルウェアワーシングウェブシュアレーバーは、interceptttprequestSeyreatheyreachtheTheTheHandlerを使用して、カットカッティングの機能性を有効にします

Golangアプリケーションの優雅なシャットダウンをどのように処理しますか? Golangアプリケーションの優雅なシャットダウンをどのように処理しますか? Sep 21, 2025 am 02:30 AM

GracefulshutdownsingoApplicationSaresentialForreliability、retureved vedeved bytevedeved byteved interceptingsignalsigintandsig themusinging theos/signalpackagetoinitiateShutdownprocedures、その後、spapppppstpstp.server’sshutdodd()方法

CGOとは何ですか、そしてGolangでいつ使用するか CGOとは何ですか、そしてGolangでいつ使用するか Sep 21, 2025 am 02:55 AM

cgoenablesgotocallcode、clibraries likeopenssl、accesstolow-levelsystemapis、およびperformanceptimizationを使用することを可能にします

GolangのJSONのカスタムマーシャラー/マーシャラーを作成する方法 GolangのJSONのカスタムマーシャラー/マーシャラーを作成する方法 Sep 19, 2025 am 12:01 AM

MarshaljsonとMarshaljsonのカスタマイズ可能なGO構造のJSONシリアル化と脱滑りを実装します。 2。フィールド形式の変換など、Marshaljsonを介して出力構造を制御します。 3.カスタム日付など、Unmarshaljsonを介した特別なフォーマットデータの解析。 4.再帰的な呼び出しによって引き起こされる無限ループを避けるために注意し、タイプエイリアスを使用してカスタムメソッドをバイパスします。

OracleテーブルをCSVファイルにエクスポートする方法は? OracleテーブルをCSVファイルにエクスポートする方法は? Sep 22, 2025 am 03:01 AM

回答:OracleテーブルをCSVにエクスポートすると、SQLPLUS、SQLDEVELOPER、またはUTL_FILEが使用されます。まず、SQLPlusが設定コマンドを介してフォーマットとスプール出力を設定することをお勧めします。第二に、Sqldeveloperはグラフィカルなエクスポートウィザードを提供します。上級ユーザーは、utl_fileを使用してエクスポートをプログラムできます。

Golangのフラグパッケージの使用方法 Golangのフラグパッケージの使用方法 Sep 18, 2025 am 05:23 AM

flagpackageingoparsessoscommand-linearguments bydefiningflagslikestring、int、orb​​oolusingflag.stringvar、flag.intvarなど、suchasflag.stringvar(&host "、" host "、" localhost "、" serverAddress ");

See all articles