gpt4 book ai didi

go - 使用Go从CSV数据框的列创建文本文件

转载 作者:行者123 更新时间:2023-12-01 20:27:07 26 4
gpt4 key购买 nike

我试图遍历csv文件并输出在第一列的每一行之后命名的文本文件。然后,使用该列其他行的数据填充每个文本文件。我能够将csv的内容打印到一个文本文件中,但是我无法使用for循环获取第一列的索引并使用它来创建/命名新的.txt文件,从而弄清逻辑。

package main

import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
)

func main() {
fmt.Println("Enter file path to CSV: ")
var csvFile string
_, err := fmt.Scanln(&csvFile)
if err != nil {
log.Fatal("Cannot read input")
return
}
//open file
inFile, err := os.Open(csvFile)
if err != nil {
log.Fatal(err)
}
defer inFile.Close()

readMe, _ := ioutil.ReadAll(inFile)

blankFile, err := os.Create(`C:\temp\test.txt`)
if err != nil {
log.Fatal(err)
}
defer blankFile.Close()

//write data to text file
outFile, err := blankFile.Write(readMe)
if err == io.EOF {
log.Fatalln("Failed")
} else if err != nil {
log.Fatal(err)
}
//print bytes total
fmt.Println(outFile, " bytes printed")

}

最佳答案

Take multiple columns from a csv and print each column to a new text file.

Loop over a csv and produce a new text file that will be titled after each column in row #1. Each text file will then be populated with data from the other rows for that column.



例如,
package main

import (
"encoding/csv"
"fmt"
"io"
"os"
"path/filepath"
)

func CsvFileToTxtFiles(inFile string) error {
in, err := os.Open(inFile)
if err != nil {
return err
}
defer in.Close()
r := csv.NewReader(in)
hdr, err := r.Read()
if err != nil {
return err
}
f := make([]*os.File, len(hdr))
w := make([]*csv.Writer, len(hdr))
pfx := filepath.Clean(inFile)
pfx = pfx[:len(pfx)-len(filepath.Ext(pfx))]
for i, col := range hdr {
var err error
f[i], err = os.Create(pfx + "." + col + ".txt")
if err != nil {
return err
}
defer f[i].Close()
w[i] = csv.NewWriter(f[i])
if err != nil {
return err
}
defer w[i].Flush()
}

for {
row, err := r.Read()
if err != nil {
if row == nil && err == io.EOF {
break
}
return err
}
for i, col := range row {
err := w[i].Write([]string{col})
if err != nil {
return err
}
}
}

for i := range hdr {
var err error
w[i].Flush()
err = w[i].Error()
if err != nil {
return err
}
err = f[i].Close()
if err != nil {
return err
}
}

return nil
}

func main() {
if len(os.Args) <= 1 {
usage := "usage: " + filepath.Base(os.Args[0]) + " FILE"
fmt.Fprintln(os.Stderr, usage)
return
}
inFile := os.Args[1]
err := CsvFileToTxtFiles(inFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
}

输出:
$ cat ioj.test.csv
one,two,three
1,2,3
11,22,33
$ go run ioj.go ioj.test.csv
$ cat ioj.test.one.txt
1
11
$ cat ioj.test.two.txt
2
22
$ cat ioj.test.three.txt
3
33
$

关于go - 使用Go从CSV数据框的列创建文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59997181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com