搜尋
首頁後端開發Golang決定 Golang 中 CSV 行有多少位元組

确定 Golang 中 CSV 行有多少字节

問題內容

我有一個test.csv ,我將逐行讀取它並確定每行中有多少位元組.

這應該低於 37 個位元組,因為我在 Windows 上,前兩行有 \r\n 總共新增了 4 個位元組。

foo,bar,baz
100,200,300
400,500,600

我想使用 csv.NewReader() 簡單地確定每行中有多少位元組。但是,我知道在下面的程式碼中進行位元組計數時,csv.Reader 不會計算每行中的逗號和 \n

我是否應該為每行中的逗號數 行數添加一些數學運算,為 \r\n -1 為最後一行添加 2 個位元組,因為它沒有 \r\n?這感覺有點老套,所以我寧願看看是否有更好的解決方案來解決我的位元組計數問題。

我的程式碼:

package main

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

func main() {
    file, err := os.Open("test.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    fileInfo, err := file.Stat()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("file total bytes is %d\n", fileInfo.Size())

    // init reader
    reader := csv.NewReader(file)

    // extract the header
    headers, err := reader.Read()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("headers are: %+v\n", headers)

    byteCounter := 0
    for {
        // if we reached end of file, stop
        if err == io.EOF {
            break
        }

        // read a record
        record, err := reader.Read()
        if err != nil {
            log.Fatal(err)
        }
        // loop through each record and count how many bytes
        for _, item := range record {
            byteCounter += len(item)
            fmt.Printf("record is %d bytes\n", len(item))
        }
        fmt.Println("total bytes so far is: ", byteCounter)

    }
}

正確答案


#使用 Reader.InputOffset 取得檔案中的目前位置: BD44F3686574B2610B9F6F11A1F9CFEF

https://www.php.cn/link/e2c2ff9c7fb57db574e461fbe467d84e

#要取得每行的位元組數,請減去先前的偏移量。

prevOffset := reader.InputOffset()

for {
    ...
    // read a record
    _, err := reader.Read()
    ...
    fmt.Println("line length is: ", reader.InputOffset()-prevOffset)
    prevOffset = reader.InputOffset()

}

https://www.php.cn/link/501e3f8a108d7ab9335ceecd363d113d

以上是決定 Golang 中 CSV 行有多少位元組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
GO中的字符串操縱:掌握'字符串”軟件包GO中的字符串操縱:掌握'字符串”軟件包May 14, 2025 am 12:19 AM

掌握Go語言中的strings包可以提高文本處理能力和開發效率。 1)使用Contains函數檢查子字符串,2)用Index函數查找子字符串位置,3)Join函數高效拼接字符串切片,4)Replace函數替換子字符串。注意避免常見錯誤,如未檢查空字符串和大字符串操作性能問題。

去'字符串”包裝提示和技巧去'字符串”包裝提示和技巧May 14, 2025 am 12:18 AM

你應該關心Go語言中的strings包,因為它能簡化字符串操作,使代碼更清晰高效。 1)使用strings.Join高效拼接字符串;2)用strings.Fields按空白符分割字符串;3)通過strings.Index和strings.LastIndex查找子串位置;4)用strings.ReplaceAll進行字符串替換;5)利用strings.Builder進行高效字符串拼接;6)始終驗證輸入以避免意外結果。

GO中的'字符串”軟件包:您的首選字符串操作GO中的'字符串”軟件包:您的首選字符串操作May 14, 2025 am 12:17 AM

thestringspackageingoisesential forefficientstringManipulation.1)itoffersSimpleyetpoperfulfunctionsFortaskSlikeCheckingSslingSubstringsStringStringsStringsandStringsN.2)ithandhishiCodeDewell,withFunctionsLikestrings.fieldsfieldsfieldsfordsforeflikester.fieldsfordsforwhitespace-fieldsforwhitespace-separatedvalues.3)3)

Go Bytes軟件包與字符串軟件包:我應該使用哪個?Go Bytes軟件包與字符串軟件包:我應該使用哪個?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

如何使用'字符串”軟件包逐步操縱字符串如何使用'字符串”軟件包逐步操縱字符串May 13, 2025 am 12:12 AM

Go的strings包提供了多種字符串操作功能。 1)使用strings.Contains檢查子字符串。 2)用strings.Split將字符串分割成子字符串切片。 3)通過strings.Join合併字符串。 4)用strings.TrimSpace或strings.Trim去除字符串首尾的空白或指定字符。 5)用strings.ReplaceAll替換所有指定子字符串。 6)使用strings.HasPrefix或strings.HasSuffix檢查字符串的前綴或後綴。

Go Strings軟件包:如何改進我的代碼?Go Strings軟件包:如何改進我的代碼?May 13, 2025 am 12:10 AM

使用Go語言的strings包可以提升代碼質量。 1)使用strings.Join()優雅地連接字符串數組,避免性能開銷。 2)結合strings.Split()和strings.Contains()處理文本,注意大小寫敏感問題。 3)避免濫用strings.Replace(),考慮使用正則表達式進行大量替換。 4)使用strings.Builder提高頻繁拼接字符串的性能。

GO BYTES軟件包中最有用的功能是什麼?GO BYTES軟件包中最有用的功能是什麼?May 13, 2025 am 12:09 AM

Go的bytes包提供了多種實用的函數來處理字節切片。 1.bytes.Contains用於檢查字節切片是否包含特定序列。 2.bytes.Split用於將字節切片分割成smallerpieces。 3.bytes.Join用於將多個字節切片連接成一個。 4.bytes.TrimSpace用於去除字節切片的前後空白。 5.bytes.Equal用於比較兩個字節切片是否相等。 6.bytes.Index用於查找子切片在largerslice中的起始索引。

使用GO的'編碼/二進制”軟件包掌握二進制數據處理:綜合指南使用GO的'編碼/二進制”軟件包掌握二進制數據處理:綜合指南May 13, 2025 am 12:07 AM

theEncoding/binarypackageingoisesenebecapeitProvidesAstandArdArdArdArdArdArdArdArdAndWriteBinaryData,確保Cross-cross-platformCompatibilitiational and handhandlingdifferentendenness.itoffersfunctionslikeread,寫下,寫,dearte,readuvarint,andwriteuvarint,andWriteuvarIntforPreciseControloverBinary

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。